Chame

Untitled

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