您的位置:首页 > 其它

插入,希尔,快速,堆排序实现

2014-09-07 22:08 204 查看
import javax.naming.ldap.SortControl;
import javax.xml.crypto.Data;

class QuikSort
{
public static int partion(int arr[],int s,int t)
{
int temp=arr[s];
while(s<t)
{
while(s<t&&temp<=arr[t])
t--;
arr[s]=arr[t];
while(s<t&&temp>arr[s])
s++;
arr[t]=arr[s];
}
arr[s]=temp;
return s;
}
public static void qsort(int arr[],int s,int t)
{
if (s<t) {
int mid=partion(arr,s,t);
qsort(arr, s, mid-1);
qsort(arr, mid+1, t);
}

}
public static void quikSort(int arr[])
{
qsort(arr,0,arr.length-1);
}
}
class HeapSort
{
public static void heapSort(int arr[])
{
for (int i = arr.length-1; i>0; i--) {
buildMinHeap(arr,i);
swap(arr,0,i);
}
}

private static void swap(int[] arr, int i, int j) {
// TODO Auto-generated method stub
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}

private static void buildMinHeap(int[] arr, int lastIndex) {
// TODO Auto-generated method stub
for (int i = lastIndex/2; i>=0; i--) {
int k=i;
while(2*k+1<=lastIndex)
{
int smallerIndex=2*k+1;
if (smallerIndex<lastIndex) {
if (arr[smallerIndex]>arr[smallerIndex+1]) {
smallerIndex++;
}
}
if (arr[k]>arr[smallerIndex]) {
swap(arr, k, smallerIndex);
k=smallerIndex;
}
else {
break;
}
}
}
}
}
class MergeSort
{
public static void mergeSort(int arr[])
{
sort(arr,0,arr.length-1);
}

private static void sort(int[] arr, int left, int right) {
// TODO Auto-generated method stub
if (left>=right) {
return;
}
int center=(left+right)/2;
sort(arr, left, center);
sort(arr, center+1, right);
merge(arr,left,center,right);
}

private static void merge(int[] arr, int left, int center, int right) {
// TODO Auto-generated method stub
int temparr[]=new int[arr.length];
int mid=center+1;
int third=left;
int tmp=left;
while(left<=center&&mid<=right)
{
if (arr[left]<=arr[mid]) {
temparr[third++]=arr[left++];
}
else {
temparr[third++]=arr[mid++];
}
}
while(mid<=right)
temparr[third++]=arr[mid++];
while(left<=center)
temparr[third++]=arr[left++];
while(tmp<=right)
arr[tmp]=temparr[tmp++];
}

}
public class Test3 {

public void insertSort(int arr[])
{
for (int i = 1; i < arr.length; i++) {
int temp=arr[i];
int j;
for (j = i; j>0&&temp<arr[j-1]; j--) {
arr[j]=arr[j-1];
}
arr[j]=temp;
}
}
public void shellSort(int arr[])
{
int d=arr.length/2;
while(d>0)
{
for (int i = d; i < arr.length; i++) {
int temp=arr[i];
int j;
for (j = i-d; j>=0&&temp<arr[j]; j-=d) {
arr[j+d]=arr[j];
}
arr[j+d]=temp;
}
d=d/2;
}
}
public void run()
{
int arr[]={5,2,4,1,3};
MergeSort.mergeSort(arr);
for (int i : arr) {
System.out.print(i+" ");
}
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
new Test3().run();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐