快速排序和堆排序代码

最近复习到快速排序和归并排序,根据其排序思路,自己动手实现了一下,这两种排序都用到了递归调用,在以往的项目中没有用到过递归,所以这次趁此机会练习下递归的使用。

快速排序

/**
* 快速排序
* @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;
}

猜你喜欢

转载自www.cnblogs.com/hezhiyuan/p/10831255.html