Quick actions

cmd+k|ctrl+k

Navigation

Languages

Udemy: Master Coding Interview - Insertion Sort - #172

Snippet info

Language

Csharp

Visibility

public

Author

jcurrie33

Created

2020-08-12T08:05:01Z

Updated

2020-08-12T08:05:01Z

using System;

class MainClass {
    static void Main() {
        int[] numbers = {99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0};
        //6, 8, 7
        //6, 8, 8
        Console.WriteLine(ToString(numbers));
        InsertionSort(numbers);
        Console.WriteLine(ToString(numbers));
    }
    
    public static void InsertionSort(int[] array) {
        for (int i = 1; i < array.Length; i++) {
            int temp = array[i];
            for (int j = i-1; j >= 0; j--) {
                if (temp >= array[j]) {
                    if (j+1 != i) {
                        array[j+1] = temp;
                    }
                    break;
                }
                if (temp < array[j]) {
                    array[j+1] = array[j];
                }
                if (j == 0) {
                    array[0] = temp;
                }
            }
        }
    }
    
    public static string ToString(int[] array) {
        string s = "{";
        for (int i = 0; i < array.Length; i++) {
            if (i > 0) {
                s += ", ";
            }
            s += array[i];
        }
        s += "}";
        return s;
    }
}
INFO