Insertion sort

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Method:

package com.wenzhi.util;

import java.util.Arrays;

public class Demo01 {

	/**
	 * Insertion sort
	 * @param args
	 */
	public static void main(String[] args) {
		int ary[]=new int[]{ 69,60,78,90,76,85,98,64,66,82};
		for(int i=0;i<ary.length;i++){	
			i=ary[i];
		}
		System.out.println(Arrays.toString(ary));
		System.out.println("Insertion sort");
		for(int i=1;i<ary.length;i++){
			int k=ary[i];
			int j;
			for(j= i-1;j>=0&&k<ary[j];j--){
				ary[j+1]=ary[j];
			}
			ary[j+1]=k;
			System.out.println(Arrays.toString(ary));
		}
		System.out.println("End");
		System.out.println(Arrays.toString(ary));
	}

}

The output results

[69, 60, 78, 90, 76, 85, 98, 64, 66, 82]
Insertion sort
[60, 69, 78, 90, 76, 85, 98, 64, 66, 82]
[60, 69, 78, 90, 76, 85, 98, 64, 66, 82]
[60, 69, 78, 90, 76, 85, 98, 64, 66, 82]
[60, 69, 76, 78, 90, 85, 98, 64, 66, 82]
[60, 69, 76, 78, 85, 90, 98, 64, 66, 82]
[60, 69, 76, 78, 85, 90, 98, 64, 66, 82]
[60, 64, 69, 76, 78, 85, 90, 98, 66, 82]
[60, 64, 66, 69, 76, 78, 85, 90, 98, 82]
[60, 64, 66, 69, 76, 78, 82, 85, 90, 98]
End
[60, 64, 66, 69, 76, 78, 82, 85, 90, 98]

Methods two:

package com.wenzhi.util;

import java.util.Arrays;
import java.util.Random;

public class Demo01 {

	/**
	 * Insertion sort
	 * @param args
	 */
	public static void main(String[] args) {
		int ary[]=new int[12];
		Random random=new Random();
		for(int i=0;i<ary.length;i++){
			ary[i]=random.nextInt(100);
		}
		System.out.println(Arrays.toString(ary));
		System.out.println("Insertion sort");
		for(int i=1;i<ary.length;i++){
			int k=ary[i];
			int j;
			for(j= i-1;j>=0&&k<ary[j];j--){
				ary[j+1]=ary[j];
			}
			ary[j+1]=k;
			System.out.println(Arrays.toString(ary));
		}
		System.out.println("End");
		System.out.println(Arrays.toString(ary));
	}

}

The output results

[54, 14, 75, 98, 67, 51, 98, 97, 54, 61, 27, 55]
Insertion sort
[14, 54, 75, 98, 67, 51, 98, 97, 54, 61, 27, 55]
[14, 54, 75, 98, 67, 51, 98, 97, 54, 61, 27, 55]
[14, 54, 75, 98, 67, 51, 98, 97, 54, 61, 27, 55]
[14, 54, 67, 75, 98, 51, 98, 97, 54, 61, 27, 55]
[14, 51, 54, 67, 75, 98, 98, 97, 54, 61, 27, 55]
[14, 51, 54, 67, 75, 98, 98, 97, 54, 61, 27, 55]
[14, 51, 54, 67, 75, 97, 98, 98, 54, 61, 27, 55]
[14, 51, 54, 54, 67, 75, 97, 98, 98, 61, 27, 55]
[14, 51, 54, 54, 61, 67, 75, 97, 98, 98, 27, 55]
[14, 27, 51, 54, 54, 61, 67, 75, 97, 98, 98, 55]
[14, 27, 51, 54, 54, 55, 61, 67, 75, 97, 98, 98]
End
[14, 27, 51, 54, 54, 55, 61, 67, 75, 97, 98, 98]


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Sammy at December 13, 2013 - 5:41 PM