Created
October 18, 2016 15:18
-
-
Save biskandar/4f2be4150f6652a16b931edba01aa472 to your computer and use it in GitHub Desktop.
Java: Insertion Sort 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package introalgo.chap2; | |
import java.util.Random; | |
public class InsertSort1 { | |
public static void main( String[] args ) { | |
Random random = new Random(); | |
int[] data = new int[10]; | |
for (int i = 0; i < data.length; i++) { | |
data[i] = 100 + random.nextInt(900); | |
System.out.printf("%d ", data[i]); | |
} | |
System.out.println(); | |
for (int i = 1; i < data.length; i++) { | |
int tmp = data[i]; | |
int j = i - 1; | |
for (; (j > -1) && (data[j] > tmp); j--) { | |
data[j + 1] = data[j]; | |
} | |
data[j + 1] = tmp; | |
} | |
for (int i = 0; i < data.length; i++) { | |
System.out.printf("%d ", data[i]); | |
} | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment