有可用于从一个简单的冒泡排序的整数数组许多不同种类的排序到一个稍微复杂的堆排序。有些种类比另一种更快,例如堆排序比泡泡排序更快,但是这主要影响大型数组。这是由于数字之间的交换和比较的数量。
冒泡排序
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
{
int correctNumber = i+1;
System.out.println("Value "+correctNumber+" of the sorted array which was sorted via the Bubble Sort is: "+a[i]);
}
}
}
堆排序
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
{
int correctNumber = i+1;
System.out.println("Value "+correctNumber+" of the sorted array which was sorted via the Heap Sort is: "+a[i]);
}
}
}