有可用於從一個簡單的冒泡排序的整數數組許多不同種類的排序到一個稍微複雜的堆排序。有些種類比另一種更快,例如堆排序比泡泡排序更快,但是這主要影響大型數組。這是由於數字之間的交換和比較的數量。
冒泡排序
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]);
}
}
}
堆排序
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]);
}
}
}
來源
2015-12-11 21:06:31
Dan
我不明白的排序邏輯,你可以擴大一點? – Tunaki
我需要在乞討數組中有負數,然後是零,最後是正數。 –
@Tunaki將未排序的數組變成另一個未排序的數組... ...? – redFIVE