Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

insertionSort

public class InsertionSorter {
    public static int sort(int[] randi) {
        if (randi == null || randi.length == 0) {
            return 0;
        }
        int count = 0;
        //int n = randi.length; 
        for (int i = 1; i < randi.length; ++i) { 
            int pivot = randi[i]; 
            int j = i - 1; 
            while (j >= 0 && randi[j] > pivot) {
                count++;
                randi[j + 1] = randi[j]; 
                j = j - 1; 
            } 
            randi[j + 1] = pivot; 
        }
        System.out.println("count: " + count);
        System.out.println();
        return count;
    }
    static void printArray(int arr[]) 
    { 
        //int n = arr.length; 
        for (int i = 0; i < arr.length; ++i) 
            System.out.print(arr[i] + " "); 
  
        System.out.println(); 
    } 
  
    // Driver method 
    public static void main(String args[]) 
    { 
        int arr[] = { 12, 11, 13, 5, 6, 8, 20 }; 
  
        InsertionSorter ob = new InsertionSorter(); 
        ob.sort(arr); 
  
        printArray(arr); 
    } 
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.