Selection Sort Algorithm - CSU083 - Shoolini U

Selection Sort

Introduction

This is an introduction of Straight min max algorithm.

Language: C


#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node *link;

};
void display(struct node*new){
    struct node *p;
    p = new;
    while(p->link!=NULL){
    printf("\t  %d",p->data);
    p = p->link;
    }
     printf("\t  %d",p->data);
}
struct node* getlist(){
    struct node *head;
    head = (struct node*)malloc(sizeof(struct node));
    struct node *second;
    second = (struct node*)malloc(sizeof(struct node));
    struct node *third;
    third = (struct node*)malloc(sizeof(struct node));
    struct node *fourth;
    fourth= (struct node*)malloc(sizeof(struct node));
    struct node *fifth;
    fifth = (struct node*)malloc(sizeof(struct node));
    head->data=110;
    head->link=second;
    second->data=30;
    second->link=third;
    third->data=50;
    third->link=fourth;
    fourth->data=40;
    fourth->link=fifth;
    fifth->data=100;
    fifth->link=NULL;
    return head;
}
void selectionSort(struct node *first){
    struct node* p = first, *q;
    int temp;
    while(p){
        for(q=p->link;q;q=q->link){
            if(p->data >= q->data){
                temp = p->data;
                p->data = q->data;
                q->data = temp;
            }
        }
        p = p->link; 
    }
}
int main(){
    struct node* h;
    h = getlist();
    display(h);
    selectionSort(h);
    printf("\n");
    display(h);
    return 0;
}

Language C++

#include <iostream>
using namespace std;

void selectionSort(int arr[], int n) {
    int i, j, min_idx, temp;

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

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main() {
    int n;
    cout << "Enter the number of elements: ";
    cin >> n;

    int *arr = new int[n];
    for (int i = 0; i < n; i++) {
        cout << "Enter element " << (i + 1) << ": ";
        cin >> arr[i];
    }

    cout << "Original array: ";
    printArray(arr, n);

    selectionSort(arr, n);

    cout << "Sorted array: ";
    printArray(arr, n);

    delete[] arr;
    return 0;
}