0

Any one give me code for selection sort using while statement

8th Nov 2018, 5:59 PM
Siva Sankar
Siva Sankar - avatar
2 Antworten
+ 16
#include <iostream> using namespace std; void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void selectionSort(int arr[], int n) { int min; // index of smallest element int k=0; while(k < n-1) { min = k; int j=k+1; while(j < n) { if(arr[j] < arr[min]) { min = j; } j++; } swap(&arr[min], &arr[k]); k++; } } void printArray(int arr[], int size) { int i =0; while(i < size) { cout << arr[i] << " "; i++; } } int main() { int arr[] = {5, 2, 42, 6, 1, 3, 2}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr, n); printArray(arr, n); return 0; } //here is the modified code , just converted all for() to while() loops
8th Nov 2018, 6:09 PM
Gaurav Agrawal
Gaurav Agrawal - avatar