Functions
Oct 14, 2015 at 6:12pm UTC
I wrote the below code with functions to print and sort the array from smallest to biggest. The numbers are not being sorted, what could be the reason behind it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <iostream>
using namespace std;
void arrayPrint(int A[], int n){
int i=0;
while (i<n){
cout<< A[i] << " " ;
i=i+1;
}
}
int arraySmallest (int A[], int start, int end){
int index=start;
int i=start;
while (i<=end){
if (A[i]<A[index]){
index=i;
}
i=i+1;
}
return index;
}
void swap (int x, int y) {
int temp=x;
x=y;
y=temp;
}
void selectionSort (int A[], int n){
int i=0;
while (i<n){
int k = arraySmallest(A,i,n-1);
swap(A[i],A[k]);
i=i+1;
}
}
int main(){
cout << "Please enter the number of integers" << endl;
int n;
int i=0;
cin >> n;
cout << "Please enter " << n << " integers" << endl;
int A[1024];
while (i<n) {
cin >> A[i];
i=i+1;
}
cout << "Before Sorting" << endl;
arrayPrint(A,n);
selectionSort(A,n);
cout << "After Sorting" << endl;
arrayPrint(A,n);
return 0;
}
Oct 14, 2015 at 7:11pm UTC
Topic archived. No new replies allowed.