java常用数据结构排序算法

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

import java.util.*;
public class TestSort1{
 private int[] a = {9,5,8,2,1,4,3,7};
 private int n = 8;
 public void BubbleSortedArray(){ //冒泡排序
  for(int i = 1;i<n;i++){ //n-1次通道
   for(int j = 0;j<n-i; j++){//比较n-i次
    if(a[j] > a[j+1]){
     int temp;
     temp = a[j];
     a[j] = a[j+1];
     a[j+1] = temp;
     
     }
   }
   for(int k = 0;k<n;k++){
    System.out.print(a[k]+" ");
   }
   System.out.println(); 
  }
   
 }
 public void selectSort(){ //选择排序
  for(int i = 0;i<n-1;i++){  //n-1个通道
   int k = i; //记录位置
   for(int j=i+1;j<n;j++){
    if(a[j]<a[k]){
     k = j;
    }
   }
   int temp;
   temp = a[i];
   a[i] = a[k];
   a[k] = temp;
   for(int m = 0;m<n;m++){
    System.out.print(a[m]+" ");
   }
   System.out.println(); 
  }
 }
 public void insertSort(){ //插入排序
  for(int i = 1; i<=n-1; i++){//未排序数据
   int temp = a[i];
   int j= i-1;
   if(a[i]<a[i-1]){

    a[i] = a[i-1];
    
    for(;j>=0 && temp<a[j];--j){
     a[j+1] = a[j];
    }
    
   }
   a[j+1] = temp;
   for(int m = 0;m<n;m++){
    System.out.print(a[m]+" ");
   }
   System.out.println(); 
  }
 }
 public void shellSort(){//shell排序
  for(int increment = n/2;increment>0;increment/=2){//增量
   for(int i = increment;i<n;++i){
    int temp = a[i];
    int j= i;
    for(;j>= increment;j -=increment){ //对一组增量为increment的元素进行插入排序
     if(temp < a[j-increment]){
      a[j] = a[j-increment];
     }else{
      break;
     }
    }
    a[j] = temp;
   }
   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){
  TestSort1 ts = new TestSort1();
  //ts.BubbleSortedArray();
  //ts.selectSort();
  //ts.insertSort();
  ts.shellSort();
  ts.display();
 }
}

原创粉丝点击