Document

Selection Sort

Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list.

The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it with the first element of the unsorted part. This process is repeated for the remaining unsorted portion until the entire list is sorted.




Custom Input

Array Size

Speed

Algorithm Visualization
10 5 77 3 14 9 190 7




Complexity

Worst Case O( n2 )
Average Case O( n2 )
Best Case O( n2 )
void selection(int arr[], int n) {
    int i, j, small;

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

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

int main() {
    int n, i;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d integers: ", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    selection(arr, n);
    printf("After sorting array elements are - \n");
    printArr(arr, n);

    return 0;
}            
    
public class SelectionSort
{
    void sort(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n-1; i++)
        {
            int min_idx = i;
            for (int j = i+1; j < n; j++)
                if (arr[j] < arr[min_idx])
                    min_idx = j;
            int temp = arr[min_idx];
            arr[min_idx] = arr[i];
            arr[i] = temp;
        }
    }
    void printArray(int arr[])
    {
        int n = arr.length;
        for (int i=0; i < n ; ++i)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    public static void main(String args[])
    {
        SelectionSort ob = new SelectionSort();
        int arr[] = {64,25,12,22,11};
        ob.sort(arr);
        System.out.println("Sorted array");
        ob.printArray(arr);
    }
}
def selection_sort(arr):
    for i in range(len(arr) - 1):
        min_idx = i
        for j in range(i + 1, len(arr)):
            if arr[min_idx] > arr[j]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]

def get_user_input():
    n = int(input("Enter number of elements: "))
    arr = []
    print(f"Enter {n} integers:")
    for _ in range(n):
        arr.append(int(input()))
    return arr

if __name__ == "__main__":
    arr = get_user_input()
    selection_sort(arr)
    print("Sorted array")
    for i in range(len(arr)):
        print(arr[i], end=" ")