快速排序java
package codeB;
public class 快速排序
{
//METHOD SIGNATURE BEGINS, THIS METHOD IS REQUIRED
public static void quickSort(int[] arr,int low,int high)
{
// INSERT YOUR CODE HERE
if(low<high){
int index=getIndex(arr,low,high);
quickSort(arr,0,index-1);
quickSort(arr,index+1,high);
}
}
public static int getIndex(int[] arr,int low,int high){
int tmp=arr[low];
while(low<high){
while(low<high&&arr[high]>=tmp){
high--;
}
arr[low]=arr[high];
while(low<high&&arr[low]<=tmp){
low++;
}
arr[high]=arr[low];
}
arr[low]=tmp;
return low;
}
public static void main(String[]args){
int[] arr = { 49, 38, 65, 97, 23, 22, 76, 1, 5, 8, 2, 0, -1, 22 };
quickSort(arr, 0, arr.length - 1);
System.out.println("排序后:");
for (int i : arr) {
System.out.println(i);
}
}
// METHOD SIGNATURE ENDS
}
堆排序:
package codeB;
import java.util.*;
public class 堆排序算法 {
public static void main(String[] args) {
int a[] = {9,8,7,6,5,43,1};
//构建大顶堆
for(int i = a.length/2 - 1; i >= 0;i -- )
{
adjustDui(a,i,a.length);
}
//将大顶堆的顶部元素和最后的元素交换后,最后重构大顶堆
for(int i = a.length-1;i >0;i--)
{
swap(a,0,i);
adjustDui(a,0,i);
}
System.out.println(Arrays.toString(a));
}
//该方法的意义是将堆顶的左右子树中最大的值,放入堆顶
public static void adjustDui(int a[],int start,int end)
{
//首先将堆顶的节点放入temp
int temp = a[start];
for(int i = start*2+1 ;i < end;i = i*2+1)//从左子树开始一直找到堆底
{
if(i+1 < end && a[i] < a[i+1] ){
i++;
}
if(a[i] > temp)//此两步选出左右子树中较大的一位,然后,替换掉自己的父亲,并获取替换的位置,在下一次循环中调整变换的节点
{
a[start] = a[i];
start = i;
}
else{
break;
}
}
a[start] = temp;
}
//交换数组的两个index
public static void swap(int a[],int i,int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}