Program in C and C++ to sort an array using selection sort technique
C Program
#include<stdio.h> void selection_sort(int *arr, int size){ int i, j, min, minIndex ; for(i = 0; i < size - 1; i++){ min = arr[i]; minIndex = i; for(j = i + 1; j < size; j++){ if(arr[j] < min){ min = arr[j]; minIndex = j; } } arr[minIndex] = arr[i]; arr[i] = min; } } int main(){ int arr[] = {33, 22, 55, 44, 66, 11}; int size = 6, i; printf("Selection Sort Technique ..\n\n"); printf("\nBefore sorting.."); for(i = 0; i < size; i++){ printf("%4d", arr[i]); } // selection_sort(arr, size); printf("\nAfter sorting.."); for(i = 0; i < size; i++){ printf("%4d", arr[i]); } printf("\n\n"); return 0; }
C++ Program
#include<iostream> using namespace std; void selection_sort(int *arr, int size){ int i, j, min, minIndex; for(i = 0; i < size - 1; i++){ min = arr[i]; minIndex = i; for(j = i + 1; j < size; j++){ if(arr[j] < min){ min = arr[j]; minIndex = j; } } arr[minIndex] = arr[i]; arr[i] = min; } } int main(){ int arr[] = {15, 6, 25, 44, 66, 11, 65, 3, 45}; int size = 9, i; cout<<"Selection sort Technique..\n\n"; cout<<endl<<"Before sorting.."; for(i = 0; i < size; i++){ cout<<" "<<arr[i]; } // selection_sort(arr, size); cout<<endl<<"After sorting.."; for(i = 0; i < size; i++){ cout<<" "<<arr[i]; } cout<<endl<<endl; return 0; }
Output :-
Related programs
0 Comments