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