Hey guys, I got this program from my book, but need help understanding it. I will type it out with comments on what I understand, and what I don't. Really its all in the sort function i don't understand.
#include <iostream>
using namespace std;
void sort (int n);
void swap(int *p1, int *p2);
int a[10]; // initializing an array, got that.
int main(){
int i;
for (i=0; i<10;i++){ // this loop asks user to print out "i" array //element, until he has entered all of them.
cout<<"Enter array element #"<<i<<":";
cin>>a[i]; }
sort (10);// DOn't understand this function, see below.
cout<<"Here are all the array elements, sorted:"<<endl;
for (i=0; i<10; i++)
cout<<a[i]<<",";
cin.get();
cin.get();
return 0;
}
void sort (int n){ // I am completely lost here.
int i, j, low;
for (i = 0; i<n; i++){
low = i;
for (j = i+1; j<n; j++)
if(a[j] < a[low])
low = j;
if (i != low)
swap (&a[i], &a[low]);
}
}
void swap(int *p1, int *p2){ //I understand this.
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
This is an implementation of selection sort where you keep picking the smallest element from the remaining list.
You should get a better book (e.g. The C++ Primer), as the author of yours is a beginner at C++ - you'd risk learning bad habits and things that might be just plain wrong if you continue working with that book.
void sort (int n) //the function takes the length of the array
{ //since the array in global scope we can access it here
int i, j, low;
for (i = 0; i<n; i++)
{
low = i; //assumes that the lowest integer is the first index
for (j = i+1; j<n; j++) //compare to every other integers in the array
if(a[j] < a[low]) //if our assumption is greater than other integer
low = j; //then we change it to the lower one
if (i != low) //no point of swapping if it is equal to itself
swap (&a[i], &a[low]); //just make a swap
}
}