经典算法之插入排序

问题

   有一数组a,长度为n,把数组中的元素小到大重新排列。

 

思路

   我们把数组分为已排序和未排序两部分,把未排序的元素一次一个插入到已排序部分的合适位置上。已排序部分逐渐增大,直到整个数组变成有序的。

   一趟排序:假设从第n个元素开始是无序的,而其前面n-1个元素是有序的。把a[n]取出来放入temp中。然后用temp与前面的元素比较。(1)如果比前面的元素小,则前面的元素后移一位(2)如果比前面的元素大则插入到后面的位置,这一趟排序完成。这时已排序元素增加为n个。如此类推。

1

 

核心代码:

static void sort(int[] array) {
    
int temp;
    
int i,j;
    
int length = array.length;
        
    
for(i = 1; i < length; i++) {
        temp 
= array[i];
        
for(j = i-1; j >=0; j--) {
        
if(temp < array[j]) {
        array[j
+1= array[j];
        } 
else {
        
break;
        }
    }
    array[j
+1= temp;
    }
}

 

全部代码:

package com.icescut.classic.algorithm;

public class InsertSort {

    
public static void main(String[] args) {
    
int[] array = {10,-3,5,34,-34,5,0,9};        //test data
    sort(array);
    
for(int el : array) {
        System.out.print(el 
+ " ");
    }
    }
    
    
static void sort(int[] array) {
    
int temp;
    
int i,j;
    
int length = array.length;
        
    
for(i = 1; i < length; i++) {
        temp 
= array[i];
        
for(j = i-1; j >=0; j--) {
        
if(temp < array[j]) {
            array[j
+1= array[j];
        } 
else {
            
break;
        }
        }
        array[j
+1= temp;
    }
    }
}

posted @ 2009-10-26 08:28  小冰  阅读(423)  评论(0编辑  收藏  举报