1. 程式人生 > >快速排序和堆排序代碼

快速排序和堆排序代碼

調用 兩種 ++ null base uic flag arr ase

最近復習到快速排序和歸並排序,根據其排序思路,自己動手實現了一下,這兩種排序都用到了遞歸調用,在以往的項目中沒有用到過遞歸,所以這次趁此機會練習下遞歸的使用。

快速排序

/**
* 快速排序
* @param nums
* @param i 數組nums的起始下標
* @param j 數組nums的結束下標(包含)
* @return
*/

public static int[] quickSort(int[] nums, int i, int j) {
int base = nums[i];
int oldI = i;
int oldJ = j;
int flag = 0;
do {
for (; j - i > 0; j--) if (nums[j] < base) break;
for (; j - i > 0; i++) if (nums[i] > base) break;
if (i == j) {
nums[oldI] = nums[j];
nums[j] = base;
flag = i;
break;
} else {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
} while (i < j);
if (oldI < flag - 1) quickSort(nums, oldI, flag - 1);
if (oldJ > flag + 1) quickSort(nums, flag + 1, oldJ);
return nums;
}
歸並排序
/**
* 歸並排序
* @param nums
* @param i 數組nums的起始下標
* @param j 數組nums的結束下標(包含)
* @return
*/
public static int[] mergeSort(int[] nums, int i, int j)
{
int[] result = null;
if(nums.length == 1)
{
result = nums;
}
else
{
int half = (i + j)/2;
int[] head = new int[half- i + 1];
int[] tail = new int[j- half];
System.arraycopy(nums,i,head,0,half- i + 1);
System.arraycopy(nums,half + 1,tail,0,j- half);
if(head.length == 1 && tail.length == 1 )
{
result = compare(head,tail);
}
else
{
int[] result1 = new int[head.length];
int[] result2 = new int[tail.length];
if(head.length >= 1 )
{
result1 = mergeSort(head,0,head.length - 1);
}
if(tail.length >= 1 )
{
result2 = mergeSort(tail,0,tail.length - 1);
}
result = compare(result1,result2);
}
}

return result;
}
public static int[] compare(int[] head, int[] tail)
{
int[] result = new int[head.length + tail.length];
int i = 0,j = 0,k = 0;
while(i < head.length && j < tail.length)
{
if(head[i] < tail[j] )
{
result[k] = head[i];
i++;
}
else
{
result[k] = tail[j];
j++;
}
k++;
}
if(i == head.length && j < tail.length)
{
for(int p = k; p < head.length + tail.length; p++)
{
result[k] = tail[j];
j++;
k++;
}
}
else if(j == tail.length && i < head.length)
{
for(int p = k; p < head.length + tail.length; p++)
{
result[k] = head[i];
i++;
k++;
}
}
return result;
}

快速排序和堆排序代碼