+ 2

why i m not getting correct answer

this is an implementation of selection_sort algorithm but when i try to access any index above 0 i only get 3 .why? https://code.sololearn.com/c6fBg9wTUAC7/#cpp

11th Oct 2017, 11:38 AM
shobhit
shobhit - avatar
1 Odpowiedź
+ 1
#include <iostream> using namespace std; // sorting array using selection sort algorithm // q is query index int sorting(int unsorted[],int n,int q) { for(int i=0;i<n-1;i++) { int minimum = unsorted[i]; for(int u=i+1;u<n;u++) { // Here you are iterating from 1 to 5, then 2 to 5, then 3 to 5 // setting unsorted[i] to the smallest number, ie 3 // 9,7,5,8,3} smallest 3 // 7,5,8,3} smallest 3... // 5,8,3} // 8,3} if(unsorted[u]<unsorted[i]) minimum=unsorted[u]; } unsorted[i]=minimum; } return unsorted[q]; // end result {1,3,3,3,3,3} } int main() { int arr[] = {1,9,7,5,8,3}; int q; cin >> q; cout<<sorting(arr,6,q)<<endl; return 0; } To remedy this I would start with swapping instead of overwriting. Also the "arr" array is being directly modified by the function, so if you want to you can print the sorted array in main like this. for(int i = 0; i < 6; i++){ cout << arr[i] << endl; }
11th Oct 2017, 2:09 PM
nevu
nevu - avatar