Close

More practice: sorting

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):

  1. Find the smallest number in the list
  2. Swap it with the first element
  3. Find the next smallest number
  4. Swap with the second element
  5. 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;
}
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Tumblr
  • Twitter

Related posts:

  1. No Fun with Roman Numerals
  2. Storing a CSV text file into a C Struct
  3. Quick and Dirty Test for Primes
  4. July 23 ‘09 Bullets
  5. 14 Random Things…

Or, you can just browse

This post has no comments yet. Be the first? →

Post a Comment

Your email is never shared. Required fields are marked *

*
*

By submitting a comment here you grant this site a perpetual license to reproduce your words and name/web site in attribution.