Insertion Sort - Part 2

Sort by

recency

|

565 Discussions

|

  • + 0 comments

    def insertionSort2(n, arr):

    for i in range(1, n):
        for j in range(i, 0, -1):
            if arr[j]<arr[j-1]:
                arr[j], arr[j-1] = arr[j-1], arr[j
            else:
                break
        print(*arr)
    
  • + 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

    C#

    public static void insertionSort2(int n, List<int> arr)
    {
        for (int i = 1; i < n; i++)
        {
            for (int j = 0; j < i; j++)
            {
                if (arr[j] > arr[i])
                {
                    var temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
    
            Console.WriteLine(string.Join(" ", arr));
        }
    }
    
  • + 0 comments

    My C code 😎😁

    void insertionSort2(int n, int arr_count, int* arr) {
        for(int i = 1;i<n;i++){
            int cle = arr[i];
            int j = i -1;
            while(j>= 0 && arr[j]>cle){
                arr[j+1] = arr[j];
                j--;
            }
            arr[j+1] = cle;
            for(int i =0;i<n;i++){
                printf("%d ",arr[i]);
            }
            printf("\n");
        }
    }
    
  • + 0 comments
    def insertionSort2(n, arr):
        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(map(str, arr)))
    
    # Example usage:
    n = int(input())
    arr = list(map(int, input().split()))
    insertionSort2(n, arr)