Home coding Write a program to implement selection sort algorithm.

Write a program to implement selection sort algorithm.

0
141

Given an integer array we have to sort an array using selection sort algorithm.

Example:

input:arr[]={4,5,2,5,7}
output:{2,4,5,5,7}

Logic:

step 1- it will sort an array by find minimum element repeatedly.
step 2-put them in sorted part.
step 3-repeat step 1 again.

Code-

#include <iostream>
using namespace std;
void swap(int *a, int *b) {
  int temp = *a;
  *a = *b;
  *b = temp;
}

void selection(int array[], int size) {
  for (int step = 0; step < size - 1; step++) {
    int min_idx = step;
    for (int i = step + 1; i < size; i++) {
      if (array[i] < array[min_idx])
        min_idx = i;
    }
    swap(&array[min_idx], &array[step]);
  }
}
int main() {
  int arr[] = {2, 32, 15, 15, 2};
  int size = sizeof(arr) / sizeof(arr[0]);
  selection(arr, size);
  for (int i = 0; i <size; i++) {
    cout<<arr[i] << " ";
  }
}

Output:

2 2 15 15 32 

Time complexity:0(N*N)

Space Complexity:O(1)

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here