`
jackey25
  • 浏览: 109173 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

JAVA排序算法实现代码-插入排序

阅读更多
插入排序算法步骤
1.从有序数列和无序数列{a2,a3,…,an}开始进行排序;
2.处理第i个元素时(i=2,3,…,n) , 数列{a1,a2,…,ai-1}是已有序的,而数列{ai,ai+1,…,an}是无序的。用ai与ai-1,a i-2,…,a1进行比较,找出合适的位置将ai插入;
3.重复第二步,共进行n-1次插入处理,数列全部有序。

我的做法(感觉代码有点乱)
import java.util.ArrayList;
import java.util.List;

public class InsertSort {
	 public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // 预设数据数组

	 public static void main(String[] args){
		 List list = new ArrayList();
	   for(int jj : a){
		   InsertSort(a);
		   list.add(a[a.length-1]);
		   a[a.length-1] = 0;
	   }
	   for(int ee =0;ee<list.size();ee++){
		   System.out.println(list.get(ee));
	   }
	   System.out.println();
	 }
	 public static void InsertSort(int[] a){

		 List listSource = new ArrayList();
		 int tmp = 0;
		 for(int j=0 ; j<a.length; j++){
			 if(j == a.length-1){
				 continue;
			 }
			 if(a[j]>a[j+1])
			 {
				 tmp = a[j];
				 a[j] = a[j+1];
				 a[j+1] = tmp;
			 }
		 }
		 System.out.println("The biggest is : "+ a[a.length-1]);
	 }

}



参考一下网上的例子 :

public class Test {
  public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // 预设数据数组

  public static void main(String args[]) {
    int i; // 循环计数变量
    int Index = a.length;// 数据索引变量

    System.out.print("排序前: ");
    for (i = 0; i < Index - 1; i++)
      System.out.print(" " + a[i] + " ");
    System.out.println("");

    InsertSort(Index - 1); // 选择排序
    // 排序后结果
    System.out.print("排序后: ");
    for (i = 0; i < Index - 1; i++)
      System.out.print(" " + a[i] + " ");
    System.out.println("");
  }

  public static void InsertSort(int Index) {
    int i, j, k; // 循环计数变量
    int InsertNode; // 欲插入数据变量

    for (i = 1; i < Index; i++) // 依序插入数值
    {
      InsertNode = a[i]; // 设定欲插入的数值
      j = i - 1; // 欲插入数组的开始位置
      // 找适当的插入位置
      while (j >= 0 && InsertNode < a[j]) {
        a[j + 1] = a[j];
        j--;
      }
      a[j + 1] = InsertNode; // 将数值插入
      // 打印目前排序结果
      System.out.print("排序中: ");
      for (k = 0; k < Index; k++)
        System.out.print(" " + a[k] + " ");
      System.out.println("");
    }
  }
}



运行结果 
排序前: 10 32 1 9 5 7 12 0 4 
排序中: 10 32 1 9 5 7 12 0 4 
排序中: 1 10 32 9 5 7 12 0 4 
排序中: 1 9 10 32 5 7 12 0 4 
排序中: 1 5 9 10 32 7 12 0 4 
排序中: 1 5 7 9 10 32 12 0 4 
排序中: 1 5 7 9 10 12 32 0 4 
排序中: 0 1 5 7 9 10 12 32 4 
排序中: 0 1 4 5 7 9 10 12 32 
排序后: 0 1 4 5 7 9 10 12 32 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics