Search code examples
c#arrayssorting

How to sort first M elements in N length array?


I have some tasks about sorting arrays in C#. I've been trying everything I could think of - no luck.

The task is to sort an array of integers by known sorting algorithms (insertion, selection, bubble, quick). Thing is, I have to sort ONLY the smallest M elements.

Example: I have an array of 7 elements 2 9 8 3 4 15 11 and I need to sort the smallest 3 elements so that my array becomes 2 3 4 9 8 15 11.

Please help, I can't seem to find anything neither here in SO, nor anywhere through Google. I don't ask to do all the algorithms for me, I just need one of those just to get hold on how's that possible.

E: Thank you for your thoughts. I've reviewed all of your recommendations and have accomplished to make an insertion sort like that:

static int[] insertSort(int[] arr, out int swaps, out int checks) {
    int step = 0;
    swaps = 0;
    checks = 0;
    for (int i = 0; i < arr.Length; i++) {
        int min = arr[i], minind = i;
        for (int j = i + 1; j < arr.Length; j++) {
            checks++;
            if (arr[j] < min) {
                min = arr[j];
                minind = j;
            }
        }
        int temp = arr[minind];
        if (step < M) {
            for (int j = minind; j > i; j--) {
                swaps++;
                arr[j] = arr[j - 1];
            }
            arr[i] = temp;
            swaps++;
            step++;
        }
    }
    return arr;
}

Swaps and checks - requirement for my application.

P.S. I've seen many times that SO doesn't like to do homework for someone. That's why I haven't asked for code, I've just asked for thoughts on how to accomplish that.

Thanks again for those who have helped me out here.


Solution

  • Since there is no efficiency limitations:

    1. Set i to 0.
    2. Look for the minimum among the not sorted elements.
    3. Insert it into the position i, shift the array.
    4. Increment i.
    5. Repeat M times.

    Complexity is O(N * M).