Sunday, January 10, 2016

Bubble Sort, Selection Sort and Insertion Sort

Sorting Algorithms with complexity o(n^2)

Bubble Sort

public class BubbleSort {
      public static void main(String[] args) {
            int num[] = new int[] { 20, 13, 23, 19, 29, 1 };
            for (int i = 0; i <= (num.length) - 2; i++) {
                  for (int j = 0; j <= (num.length) - 2 - ij++) {
                        if (num[j] > num[j + 1]) {
                              int temp = num[j];
                              num[j] = num[j + 1];
                              num[j + 1] = temp;
                        }
                  }
            }
            StringBuffer sb = new StringBuffer();
            for (int i : num) {
                  sb.append(i).append(" ");
            }
            System.out.println(sb.toString());
      }
}

Selection Sort

package com.javaetutorials;

/*Finding the smallest element and swapping with the first element ,
 thus fixing the starting position to the last position*/

public class SelectionSort {
      public static void main(String[] args) {
            int num[] = new int[] { 20, 13, 23, 19, 29, 1 };
            for (int i = 0; i <= num.length - 2; i++) {
                  // Min index is the first element of unsorted list
                  int min = i;

                  /*
                   * Find minimum element index in Unsorted List. Update the Minimum
                   * element index.
                   */
                  for (int j = i + 1; j <= num.length - 1; j++) {
                        if (num[j] < num[min])
                              min = j;
                  }
                  int temp = num[min];
                  num[min] = num[i];
                  num[i] = temp;
            }
            for (int arr : num)
                  System.out.print(arr + ",");
      }
}

Insertion Sort

package com.javaetutorials;

public class InsertionSort {
          public static void main(String[] args) {
                   int num[] = new int[] { 20, 13, 23, 19, 29, 1 }, i, j, key;
                   for (i = 1; i <= num.length - 1; i++) {
                             key = num[i];
                             j = i - 1;
                             while (j >= 0 && key < num[j]) {
                                      num[j + 1] = num[j];
                                      j--;
                             }
                             num[j + 1] = key;
                   }
                   for (int arr : num)
                             System.out.print(arr + ",");
          }
}

< in highlighted portion making it Stable Sort whereas <= will move the element to left and thus making it Unstable Sort.


No comments:

Post a Comment