Insertion Sort - Part 2

Sort by

recency

|

579 Discussions

|

  • + 0 comments

    There's more than one way to do it,

    def insertionSort2(n, arr):
        if n <= 1:
            return
        for i in range(1, n):
            j = i
            while j > 0 and arr[j-1] > arr[j]:
                arr[j], arr[j-1] = arr[j-1], arr[j]
                j -= 1
            print(" ".join(map(str, arr)))
    
  • + 0 comments
    def insertionSort2(n, arr):
        # Write your code here in python
        for i in range(1, n):
            for j in range(i-1,-1,-1):
                if arr[i] < arr[j]:
                    arr[i], arr[j] = arr[j], arr[i]
                    i -= 1
            print(*arr)
        return arr
    
  • + 0 comments
    def insertionSort2(n, arr):
        # Write your code here
        
        for i in range(1, n):
            key = arr[i]
            j = i - 1
            while j >= 0 and key < arr[j]:
                arr[j+1] = arr[j]
                j -= 1
            arr[j+1] = key
            print(" ".join(str(x) for x in arr))
    
  • + 0 comments

    Here is problem solution in python java c++ c and Javascript - https://programmingoneonone.com/hackerrank-insertion-sort-part-2-problem-solution.html

  • + 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;
        }
    }