Insertion Sort - Part 2

Sort by

recency

|

570 Discussions

|

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/419S35Kb4Nw

    void insertionSort2(int n, vector<int> arr) {
        for (int i = 1; i < n; i++) {
            int current = arr[i];
            int j = i - 1;
            while (j >= 0 && arr[j] > current) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = current;
            for(int i = 0; i < n; i++) cout << arr[i] << " ";
            cout << endl;
        }
    }
    
  • + 0 comments

    Solution from my side (Python)

    def insertionSort1(n, arr):
        for i in range(len(arr)-1):
            if(arr[i]>arr[i+1]):
                temp = arr[i+1]
                arr[i+1]=arr[i]
                arr[i]=temp
                for j in range(i+1):
                    for k in range(j,i+1):
                        if(arr[j]>arr[k]):
                            temp = arr[k]
                            arr[k] = arr[j]
                            arr[j] = temp
                for num in arr:    
                    print(num,end=' ')
                print()
            else:
                for num in arr:    
                    print(num,end=' ')
                print()
    
  • + 0 comments

    My answer in Typescript, simple

    function insertionSort2(n: number, arr: number[]): void {
        /**
         * again, simple as question request
         * loop [i] from 1, call [insertionSort1] by that sub-array
         * print each loop
         * 
         * note:    [insertionSort1] is answer of previous question 
         *          (return arr instead of print)
         */
        for (let i = 1; i < arr.length; i++) {
            arr = [
                ...insertionSort1(arr.slice(0, i + 1)),
                ...arr.slice(i + 1)
            ]
            console.log(arr.join(' '))
        }
    }
    
  • + 0 comments

    Do not let the sample explanation confuse you? You don't need any further inspection if the current value is greater than the one preceding. The solution to this problem is same as insertionsort1 except for printing and scope.

  • + 0 comments

    my Java 8 solution:

        public static void insertionSort2(int n, List<Integer> arr) {
            for (int i=1; i < n; i++) {
                for (int j=0; j < i; j++) {
                    if (arr.get(i) < arr.get(j)) {
                        int toInsert = arr.remove(i);
                        arr.add(j, toInsert);
                    }
                }
                StringBuilder sb = new StringBuilder();
                arr.forEach(item -> sb.append(item + " "));
                System.out.println(sb.toString().trim());
            }
        }