Easy Array Problems C

Selection Sort Program in C with Output

Sort an integer array in ascending order in C using selection sort.

  • TimeO(n^2) in the best, average and worst case
  • SpaceO(1)
  • Hints3
  • Read3 min
Quick answer

Selection sort in C finds the smallest element in the unsorted part of the array and swaps it with the first unsorted position. After pass 1 the smallest value is at index 0, after pass 2 the second smallest is at index 1, and so on. It needs n - 1 passes, makes n(n - 1)/2 comparisons, so it is O(n^2), but it does at most n - 1 swaps.

Selection sortMinimum indexNested loopsPassing arrays to functions
1

Problem statement

Write a selection sort program in C. Given an int array, sort it in ascending order in place, and print the array after every pass so you can see how it changes.

Use {64, 25, 12, 22, 11} as the sample array.

Input

An integer array arr of size n.

Output

The array after each pass, then the sorted array.

Examples

Example 1
Input{64, 25, 12, 22, 11}
Output11 12 22 25 64

11 is selected first, then 12, then 22, then 25.

Example 2
Input{3, -1, 3, 0}
Output-1 0 3 3

Negative numbers and duplicates sort the same way.

Constraints

  • 1 <= n <= 1000 for this simple version
  • Duplicates and negative values are allowed
2

Think before you code

Reveal the questions to ask yourself first
  • Which value belongs at index 0 at the end?
  • Should you remember the smallest value or its index? Why?
  • How many passes are needed for n elements?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Keep min as an index. You need the index to swap.
2 Hint 2
The inner loop starts at i + 1, because everything before i is already sorted.
3 Hint 3
Swap once per pass, after the inner loop finishes.
4

Approach

Reveal the step-by-step approach

Selection sort logic

The array has two parts: sorted on the left and unsorted on the right. Each pass:

  1. Set min = i.
  2. Scan j from i + 1 to n - 1. If arr[j] < arr[min], set min = j.
  3. Swap arr[i] and arr[min] if min is not i.

The outer loop runs from i = 0 to n - 2. When only one element is left, it is already in place.

Passing an array to a function in C

An array passed to a function becomes a pointer to its first element, so the function sorts the caller's array directly. The function cannot find the size by itself, so pass n as well. In main, sizeof(arr) / sizeof(arr[0]) gives the count.

The inner scan is the same idea as finding the smallest element; see what is an array for the basics.

5

Dry run

Walk through the example step by step

{64, 25, 12, 22, 11}:

pass | i | smallest in arr[i..4] | swap     | array after
-----+---+-----------------------+----------+------------------
1    | 0 | 11 at index 4         | 64, 11   | 11 25 12 22 64
2    | 1 | 12 at index 2         | 25, 12   | 11 12 25 22 64
3    | 2 | 22 at index 3         | 25, 22   | 11 12 22 25 64
4    | 3 | 25 at index 3         | none     | 11 12 22 25 64

Pass 4 finds that 25 is already in place, so no swap happens.

6

Solution

Reveal the full C solution
solution.c
#include <stdio.h>

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int min = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[min]) {
                min = j;
            }
        }
        if (min != i) {
            int temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }
        printf("After pass %d: ", i + 1);
        printArray(arr, n);
    }
}

int main(void) {
    int arr[] = {64, 25, 12, 22, 11};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original:     ");
    printArray(arr, n);
    selectionSort(arr, n);
    printf("Sorted:       ");
    printArray(arr, n);
    return 0;
}

Output:

Original:     64 25 12 22 11
After pass 1: 11 25 12 22 64
After pass 2: 11 12 25 22 64
After pass 3: 11 12 22 25 64
After pass 4: 11 12 22 25 64
Sorted:       11 12 22 25 64

The array was sorted after pass 3, but selection sort does not know that. It still runs pass 4 and scans the rest. That is why its best case is also O(n^2).

Selection sort in C with user input

#include <stdio.h>

int main(void) {
    int n;
    printf("Enter size: ");
    scanf("%d", &n);
    int arr[n];
    printf("Enter %d numbers: ", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    for (int i = 0; i < n - 1; i++) {
        int min = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[min]) {
                min = j;
            }
        }
        int temp = arr[i];
        arr[i] = arr[min];
        arr[min] = temp;
    }

    printf("Sorted: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    return 0;
}
Enter size: 4
Enter 4 numbers: 3 -1 3 0
Sorted: -1 0 3 3

int arr[n] is a variable-length array, allowed since C99. If your compiler does not support it, declare a fixed size such as int arr[100] and keep n at 100 or less.

Selection sort in C, descending order

Select the largest value each pass. Only the comparison and the variable name change:

int max = i;
for (int j = i + 1; j < n; j++) {
    if (arr[j] > arr[max]) {
        max = j;
    }
}
/* swap arr[i] and arr[max] */

For {64, 25, 12, 22, 11} this gives 64 25 22 12 11.

Sorting programs in C: comparison

Point Selection sort Bubble sort (with flag) Insertion sort
Best case O(n²) O(n) O(n)
Worst case O(n²) O(n²) O(n²)
Swaps at most n - 1 up to n(n - 1)/2 shifts instead of swaps
Stable No Yes Yes

Not stable: in {4a, 4b, 1}, pass 1 swaps 4a with 1, giving {1, 4b, 4a}. The two 4s changed their order.

The Java version, with a Class 10 style program, is on selection sort in Java. Also see bubble sort and time complexity and Big O.

TimeO(n^2) in the best, average and worst case
SpaceO(1)
7

Review before the interview

Common mistakes

  • Swapping inside the inner loop every time a smaller value is found. It still sorts, but with many extra swaps, and it is no longer selection sort.
  • Comparing arr[j] with arr[i] instead of arr[min], which loses track of the smallest.
  • Starting the inner loop at 0 instead of i + 1.
  • Using sizeof(arr) inside the function. There arr is a pointer, so you get the pointer size, not the array size.

Edge cases to test

  • One element: the outer loop does not run.
  • Already sorted: every comparison still happens, but no swaps with the min != i check.
  • All equal values: no swaps.
  • Negative numbers and duplicates sort correctly.

Interview follow-ups

  • How many comparisons does selection sort make for n = 10?
  • Can you find both the smallest and the largest in one pass and fill from both ends?
  • Can selection sort be made stable?

Keep practising

Building your programming basics?

CodeBegun’s programs build problem-solving with mentor review and mock interviews, online or in Madhapur, Hyderabad.

Chat with us