I wanted to try my hand at sorting, this time, because it’s something I never got around to doing in the past. So I quickly whipped up around ten thousand random integers, put it in a text file, and went to work. My first idea was to do a bubble sort, but the idea of performing comparisons two at a time Instead, I went with the following algo (I forgot what it’s called):
- Find the smallest number in the list
- Swap it with the first element
- Find the next smallest number
- Swap with the second element
- Repeat until the last element is reached
I placed ten thousand random integers onto a file, “intlist”, read from it, and placed the values in a vector; I decided to use a vector because I didn’t want to have to bother re-learning linked lists, and I wanted to try various amounts of random numbers later on. Note that, at this point, performance is not yet an issue; I just wanted to do a sort. Code after the jump.
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int findSmallest(vector<int> num, int start, int arrsize){
int min = num[start], indexOfMin = start;
for( int index = start + 1; index < arrsize; index++ ){
if(num[index] < min){
min = num[index];
indexOfMin = index;
}
}
return indexOfMin;
}
int main( void ){
vector<int> temp;
ifstream intFile;
intFile.open("intlist");
while( intFile ){
int i;
intFile >> i;
temp.push_back(i);
}
const int arrsize = temp.size();
int smallest = 0;
for( int i = 0; i < arrsize-1; i++ ){
smallest = findSmallest(temp, i, arrsize);
if( temp[i] > temp[smallest] ){
int holder = temp[i];
temp[i] = temp[smallest];
temp[smallest] = holder;
}
}
for(int i = 0; i < arrsize-1; i++ ){
cout << temp[i] << endl;
}
return 0;
}
Related posts:
This post has no comments yet. Be the first? →