Advertisement
Chame

Untitled

Dec 20th, 2011
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. public class SelectionSort {
  2.  
  3. public static int[] data = new int[8];
  4. public static int numberOfSwaps;
  5. public static int numberOfComparisons;
  6. public static int tOrF;
  7. public static int j;
  8.  
  9. public static void randomizingArray() {
  10.  
  11. for (int i = 0; i < data.length; i++) {
  12. data[i] = (int) (1000 * Math.random()) + 1;
  13.  
  14. System.out.print(data[i] + ", ");
  15. }
  16. }
  17.  
  18. public static void selectionSort() {
  19.  
  20. for (int pass = 0; pass < data.length - 1; pass++) {
  21. for (int i = 0; i < data.length - 1; i++) {
  22. for ( j = 0; j < data.length - 1; j++) {
  23. numberOfComparisons = numberOfComparisons + 1;
  24. while (data[i] > data[j]) {
  25. tOrF = 1;
  26. }
  27. }
  28. if (tOrF == 1) {
  29. swap(data, i, j);
  30. numberOfSwaps = numberOfSwaps + 1;
  31. }
  32.  
  33. }
  34. }
  35. }
  36.  
  37. public static void swap(int[] a, int i, int j) {
  38.  
  39. int temp;
  40. temp = data[i];
  41. data[i] = data[j];
  42. data[j] = temp;
  43.  
  44. }
  45.  
  46. public static void main(String[] args) {
  47. System.out.println("Unsorted data: ");
  48. randomizingArray();
  49. selectionSort();
  50.  
  51. System.out.println("\n\nSorted data: ");
  52.  
  53. for (int i = 0; i < data.length; i++) {
  54. System.out.print(data[i] + ", ");
  55. }
  56.  
  57. System.out.println("\n");
  58. System.out.println("Number of Comparisons: " + numberOfComparisons + "\n" + "Number of Swaps: " + numberOfSwaps);
  59.  
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement