InsertionSort 直接插入排序(java)

來源:互聯網
上載者:User

標籤:print   虛擬碼   排序   sorted   插入排序   enc   public   out   ...   

排序思想:
相當於一堆數字,一開始先取出2個數排序,2個數排好序之後,再從一堆數字裡面取一個數排序,直到結束
虛擬碼:
INSERTION_SORT(A)
for j = 2 to A.length
  key = A[j]
  //Insert A[j] into sorted sequence A[1...j-1].
  i = j - 1
  while i>0 and A[i]>key
    A[i+1] = A[j]
    i = i - 1

  A[i + 1] = key

代碼:

import java.io.*;
public class InsertionSort{
public static void InsertionSort(int[] A){
  //從第二個元素開始迴圈
  for(int i=1;i<A.length;i++){
    //得到需要排序的數
    int key = A[i];
    //跟之前排好序的最大的元素開始比較,此時j為之前排好序的最大的元素的下標
    int j = i - 1;
    //迴圈比較,直到這個數>前一個數並且<後一個數
    while(j>=0&&A[j]>key){
    //比這個數大,則之前的數往後移
      A[j+1] = A[j];
      j = j - 1;
    }
    //把這個數放入數組中
    A[j + 1] = key;
  }
}


public static void main(String[] args) {
  int[] A = { 4, 6, 9, 10, 5, 3};
  InsertionSort(A);
  for(int a: A){
    System.out.print(a+" ");
  }
 }
}

 

InsertionSort 直接插入排序(java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.