java常用数据结构排序算法(续)

来源:互联网 发布:矩阵的伴随矩阵 编辑:程序博客网 时间:2024/05/29 16:26

import java.util.*;
public class QuickSort{
 private int[] a = {9,5,8,2,1,4,3,7};
 private int n = 8;
 
 public void quickSort(int[] array,int low,int high){ //快速排序
  int i,j,pivot;
  if(low>high)
   return;
  i = low;
  j = high;
  pivot = array[low];//以a[low]为基准将a分成两部分
  do{
  
   while(array[j]>=pivot && j>i){//从右向左找大于基准的记录
    j--;
   }
   if(i<j){
    array[i++] = array[j];//将表尾较小的元素移到前面
   }
   while(array[i]<=pivot && j >i)//从左向右找大于基准的记录
    i++;
   if(i<j){
    array[j--] = array[i]; //将前面较大的元素移到后面
   }
   
   
  }while(i<j);
  array[i] = pivot;//将基准放在正确位置上

  for(int m = 0;m<n;m++){
    System.out.print(a[m]+" ");
  }
  System.out.println(); 
  
  quickSort(array,low,j-1);//递归调用
  quickSort(array,j+1,high);
  
   
 }
 
 public void display(){
  System.out.println();
  System.out.println("---------------------------");
  System.out.println("       排好序的数据:       ");
  System.out.println("---------------------------");
  for(int i = 0;i<n;i++){
   System.out.print(a[i]+" ");
  }
 }
 public static void main(String[] args){
  QuickSort qs = new QuickSort();
  qs.quickSort(qs.a,0,qs.a.length-1);
  qs.display();
 }
}

public class MergeSort{//归并排序
 private int[] bridge = new int[8];
 private int[] a = {9,5,8,2,1,4,3,7};
 private int n = 8;
 public void mergeSort(int low,int high){
  if(low>=high){
   return;
  }
  int mid = (low+high)/2;
  mergeSort(low,mid);
  mergeSort(mid+1,high);
  int i = low,j = mid+1,k=low;
  while(i<=mid && j<=high){//从两个数组中取出较小的放入中间数组
   if(a[i]<=a[j]){
    bridge[k++] = a[i++];
   }else{
    bridge[k++] = a[j++];
   }
  }
  while(j<=high){//剩余部分依次放入
   bridge[k++] = a[j++];
  }
  while(i<=mid){
   bridge[k++] = a[i++];
  }
  while(low<=high){
   a[low] = bridge[low];
   low++;
  }
  for(int m = 0;m<n;m++){
    System.out.print(a[m]+" ");
  }
  System.out.println(); 
 }
 public void display(){
  System.out.println();
  System.out.println("---------------------------");
  System.out.println("       排好序的数据:       ");
  System.out.println("---------------------------");
  for(int i = 0;i<n;i++){
   System.out.print(a[i]+" ");
  }
 }
 public static void main(String[] args){
  MergeSort qs = new MergeSort();
  qs.mergeSort(0,qs.a.length-1);
  qs.display();
 }
}