Sorting

 

 

Selection

Bubble

Insertion

void selectionSort(int[] list)
{
  int min, temp;
  
  for (int outer = 0; outer < list.length - 1; outer++)
  {
    min = outer;
    for (int inner = outer + 1; inner < list.length; inner++)
    {
      if (list[inner] < list[min])
      {
        min = inner;
      }
    }
    /*swap is done in outside loop*/
    //swap list[outer] & list[flag]
    temp = list[outer];
    list[outer] = list[min];
    list[min] = temp;
  }
}

 

public static void bubbleSort(int[] list)
{
  for (int outer = 0; outer < list.length - 1; outer++)
  {
    for (int inner = 0; inner < list.length-outer-1; inner++)
    {
      if (list[inner] > list[inner + 1])
      {
        /*swap is done for every two items if the 
        first item is greater than the second –
        in the inner loop*/
list[inner] & list[inner+1]
        int temp = list[inner];
        list[inner] = list[inner + 1];
        list[inner + 1] = temp;
      }
    }
  }
}

 

void insertionSort(int[] list)
{
  for (int outer = 1; outer < list.length; outer++)
  {
    int position = outer;
    int key = list[position];
    
    /*Shift larger values to the right*/
    while (position > 0 && list[position - 1] > key)
    {
      list[position] = list[position - 1];
      position--;
    }
    list[position] = key;
  }
}

 

The Selection Sort increases efficiency over the Bubble Sort by making the comparison between an item and the smallest or largest that has been found so far in the passage through the items.

Bubble -

  • Simplest
  • Slowest

 

The Bubble Sort algorithm uses the simplest method for determining the largest item in a list: it compares two items at a time and then moves on to compare the larger of the two with the next item in the list.

If A < B and B < C, then it follows that A < C. We can skip the comparison of A and C. Hence less swapping.

 

This kind of loop is good when you’re adding items to an already sorted list.