Advertisement
Guest User

Sorts.java

a guest
Mar 22nd, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. /* Insertion sort. Modifies the original array. */
  2. public static void insertionSort(int[] array) {
  3.     // Iterate starting from index 1
  4.     for (int i = 1; i < array.length; i++) {
  5.         int element = array[i];
  6.         int j = i;
  7.  
  8.         // Move current element to the left by one step until it's in the right place.
  9.         while (j > 0 && (array[j - 1] > element)) {
  10.             array[j] = array[j - 1];
  11.             j--;
  12.         }
  13.  
  14.         array[j] = element;
  15.     }
  16. }
  17.  
  18. /* Selection sort. Modifies the original array. */
  19. public static void selectionSort(int[] array) {
  20.     int minimumIndex;
  21.     for (int i = 0; i < array.length; i++) {
  22.         minimumIndex = i;
  23.  
  24.         // Find the minimum
  25.         for (int j = i + 1; j < array.length; j++) {
  26.             if (array[j] < array[minimumIndex]) {
  27.                 minimumIndex = j;
  28.             }
  29.         }
  30.  
  31.         // Swap if needed
  32.         if (minimumIndex != i) {
  33.             int temp = array[i];
  34.             array[i] = array[minimumIndex];
  35.             array[minimumIndex] = temp;
  36.         }
  37.     }
  38. }
  39.  
  40. /* Mergesort. Modifies the original array. */
  41. public static void mergeSort(int[] array) {
  42.     int n = array.length;
  43.     if (n < 2) {
  44.         return;
  45.     }
  46.     int midpoint = n / 2;
  47.     int[] left = new int[midpoint];
  48.     int[] right = new int[n - midpoint];
  49.     for (int i = 0; i < midpoint; i++) {
  50.         left[i] = array[i];
  51.     }
  52.     for (int i = midpoint; i < n; i++) {
  53.         right[i - midpoint] = array[i];
  54.     }
  55.     mergeSort(left);
  56.     mergeSort(right);
  57.     int i = 0;
  58.     int j = 0;
  59.     int counter = 0;
  60.     while (i < left.length && j < right.length) {
  61.         if (left[i] < right[j]) {
  62.             array[counter] = left[i];
  63.             i++;
  64.         } else {
  65.             array[counter] = right[j];
  66.             j++;
  67.         }
  68.         counter++;
  69.     }
  70.     while (i < left.length) {
  71.         array[counter] = left[i];
  72.         i++;
  73.         counter++;
  74.     }
  75.     while (j < right.length) {
  76.         array[counter] = right[j];
  77.         j++;
  78.         counter++;
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement