There are many different sorts which can be used to sort an array of integers from a simple bubble sort to a slightly more complicated heap sort. Some sorts are quicker than each other, for example the heap sort is quicker than the bubble sort, however this mainly affects large arrays. This is due to the amounts of swaps and comparisons between the numbers.
Bubble Sort
public class BubbleSort
{
public void sortArray(int[] a)
{
int c, d, swap;
for(c = 1; c < a.length; c++)
{
for (d = 0; d < a.length - c; d++)
{
if (a[d] > a[d+1])
{
swap = a[d];
a[d] = a[d+1];
a[d+1] = swap;
}
}
}
for(int i=0;i<a.length;i++)
{
int correctNumber = i+1;
System.out.println("Value "+correctNumber+" of the sorted array which was sorted via the Bubble Sort is: "+a[i]);
}
}
}
Heap Sort
public class HeapSort
{
private static int[] a;
private static int n;
private static int left;
private static int right;
private static int largest;
public static void buildheap(int []a)
{
n=a.length-1;
for(int i=n/2;i>=0;i--)
{
maxheap(a,i);
}
}
public static void maxheap(int[] a, int i)
{
left=2*i;
right=2*i+1;
if(left <= n && a[left] > a[i])
{
largest=left;
}
else
{
largest=i;
}
if(right <= n && a[right] > a[largest])
{
largest=right;
}
if(largest!=i)
{
exchange(i,largest);
maxheap(a, largest);
}
}
public static void exchange(int i, int j)
{
int t=a[i];
a[i]=a[j];
a[j]=t;
}
public static void sort(int[] a0)
{
a=a0;
buildheap(a);
for(int i=n;i>0;i--)
{
exchange(0, i);
n=n-1;
maxheap(a, 0);
}
for(int i=0;i<a.length;i++)
{
int correctNumber = i+1;
System.out.println("Value "+correctNumber+" of the sorted array which was sorted via the Heap Sort is: "+a[i]);
}
}
}