Thursday 20 April 2017

Implement Insertion Sort in Java ~ foundjava

Example of Insertion Sort using Java code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class InsertionSort {
   
 public static void main(String[] args) {
  System.out.println("Hello, Java-Buddy!");
   
  MyData myData = new MyData();
  myData.show(); //Before sort
  myData.InsertionSort();
  myData.show(); //After sort
 }
  
 
 static class MyData {
   
  final static int LENGTH = 10;
  static int[] data = new int[LENGTH];
   
  MyData(){
   //Generate the random data
   for (int i = 0; i < 10; i++) {
    data[i] = (int)(100.0*Math.random());
   }
  }
   
  void InsertionSort(){
   int cur, j;
    
   for (int i = 1; i < LENGTH; i++) {
    cur = data[i];
    j = i - 1;
     
    while ((j >= 0) && (data[j] > cur)) {
     data[j + 1] = data[j];
     j--;
    }
     
    data[j + 1] = cur;
   }
  }
   
  void show(){
   for (int i = 0; i < 10; i++) {
    System.out.print(data[i] + " ");
   }
   System.out.println("\n");
  }
   
 }
}



Insertion Sort in Java

No comments:

Post a Comment