Sunday, July 5, 2015

Selection Sort - Java Code

An in-place, unstable sort

  • Worst case time complexity: O(n2)
  • Best case time complexity: O(n2)

Java Code

       public void selectionSort(int[] arr) {

              int length = arr.length;

              for (int i = 0; i < length; ++i) {

                     int nextMinPos = minIndex(arr, i, length - 1);

                     swap(arr, i, nextMinPos);
              }
       }

       public int minIndex(int[] arr, int lower, int upper) {

              int min = arr[lower];
              int minIndex = lower;

              for (int i = lower + 1; i <= upper; i++) {

                     if (arr[i] < min) {

                           min = arr[i];
                           minIndex = i;
                     }
              }

              return minIndex;
       }

       public void swap(int[] arr, int i, int j) {

              int temp = arr[i];
              arr[i] = arr[j];
              arr[j] = temp;
       }

No comments :

Post a Comment