Bubblesort

From ScriptsPedia

Jump to: navigation, search

The bubblesort is the oldest and simplest sorting method in use. But, it is the slowest one. The bubble sort works by comparing each item in the list with the item next to it, and swapping them if required. The algorithm repeats this process until it makes a pass all the way through the list without swapping any items. This causes larger values to "bubble" to the end of the list while smaller values "sink" towards the beginning of the list.

Java

A Java implementation that uses the "bubble sort algorithm" to sort an array of integers (of any size). written by talshk.

private static void bubbleSort(int[] unsortedArray)
{
 int tmp, counter, i;
 for(counter = 0; counter < unsortedArray.length - 1; counter++)
 {
  for(i = 0; i < unsortedArray.length - (counter + 1); i++)
   {
    if(unsortedArray[i] > unsortedArray[i+1])
    {
     tmp = unsortedArray[i];
     unsortedArray[i] = unsortedArray[i+1];
     unsortedArray[i+1] = tmp;
    }
   }
  }
}
Personal tools