Important alert: (current site time 7/15/2013 5:53:31 PM EDT)
 

VB icon

All the Fast Sorts

Email
Submitted on: 3/13/2002 10:06:49 PM
By: Abid Kapadya 
Level: Intermediate
User Rating: By 5 Users
Compatibility: C++ (general)
Views: 27050
(About the author)
 
     Has all the fast sorts and times it
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
//**************************************
// Name: All the Fast Sorts
// Description:Has all the fast sorts and times it
// By: Abid Kapadya
//
// Inputs:Size of vector, what u want each element to b(in MAX)
//
//This code is copyrighted and has// limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=3480&lngWId=3//for details.//**************************************

/////////////////////////////
// Sorting Template Program
//
// Author: Abid Kapadya
// Date: 2.26.02
// Period: 4
//
#include <iostream.h>
#include <iomanip.h>
#include <winSIOUX.h>
#include "SysTimer.h"// used for timing
#include "apstring.h"
#include "randgen.h"
#include "apvector.h"
void fillArray (apvector<int> &nums);
void screenOutput (const apvector<int> &nums);
void sortMenu (apvector<int> &nums);
template <class typeReplacedAtComileTime>
void swap (typeReplacedAtComileTime &a, typeReplacedAtComileTime &b);
void selectionSort (apvector<int> &list);
void insertionSort (apvector<int> &list);
void mergeSort(apvector<int> &list, int first, int last);
void quickSort (apvector<int> &list, int first, int last);
void merge(apvector<int> &a, int first, int mid, int last);
int findPosOfSmallest( apvector<int> list, int from, int to );
int main()
{
// Set the window to close when the application quits.
SIOUXSettings.autocloseonquit=true;
// Set the window to NOT display the save dialog when it quits
SIOUXSettings.asktosaveonclose=false;
apvector<int> list;
sortMenu(list);
return 0;
}
void fillArray (apvector<int> &nums)
/* Asks the user for two inputs: 1) the number of data to generate, and
2) the largest possible random integer to create. Then proceeds to fill
the array, from 1..number */
{
RandGen randGetter(100);// seed used so we all get same series of
// random numbers, this is good for comparison reasons
int numToGenerate,largestRand;
	cout << "Enter the number to generate up to(inclusive): ";
	cin >> numToGenerate;
	cout << "Enter the largest possible random integer to create: ";
	cin >> largestRand;
	
	nums.resize(numToGenerate);
	
	for( int i=0; i<numToGenerate; ++i )
	{
		nums[i]=randGetter.RandInt(0,largestRand);
	}
}
void screenOutput (const apvector<int> &nums)
// prints out the contents of the array in tabular form, 12 columns
{
cout << setiosflags( ios :: right );
for( int x=0; x<nums.length(); ++x )
{
	if( x%12 == 0 ) // 12 columns
		cout << endl;
	cout << setw(6) << nums[x] << " ";
}
}
//you can send this swap function two objects of ANY datatype and it'll "swap" them
template <class typeReplacedAtComileTime>
void swap (typeReplacedAtComileTime &a, typeReplacedAtComileTime &b)
{
typeReplacedAtComileTime temp = a;
a = b;
b = temp;
}
void selectionSort (apvector<int> &list)
{
	
	int N=list.length(), posOfSmallest;
	
	cout << endl << "SELECTION_SORT" << endl << endl;
	
	for( int outer=0; outer<N-1; outer++ )
	{
		posOfSmallest = findPosOfSmallest( list, outer, N-1 );
		swap( list[outer], list[posOfSmallest] );
	}
}
int findPosOfSmallest( apvector<int> list, int from, int to )
{
int smallestPos=from, i;
for(i=from+1; i<=to; i++)
{
	if( list[i]<list[smallestPos] )
		smallestPos=i;
}
return smallestPos;
}
	
void insertionSort (apvector<int> &list)
{
int pos;
for( int i=1; i<list.length(); ++i )
{
	pos = i;
	
	while( (pos>0) && ( list[pos-1]>list[pos] ) )
	{
		swap( list[pos-1], list[pos] );
		pos--;
	}
}
}
void mergeSort(apvector<int> &list, int first, int last)
{
int mid;
if (first == last)
;// empty case; only 1 value; do nothing
elseif (1 == last - first) // list of 2 values, swap if necessary
{
if (list[first] > list[last])
swap (list[first], list[last]);
}
else// general (recursive) case
{
mid = (first+last) / 2;
mergeSort (list, first, mid);
mergeSort (list, mid+1, last);
merge (list, first, mid, last);
}
}
void merge(apvector<int> &a, int first, int mid, int last)
/* Takes in entire vector, but will merge the following sections
together: Left sublist from a[first]..a[mid], right sublist from
a[mid+1]..a[last]. Precondition: each sublist is already in
ascending order */
{
int aPtr=first, bPtr=mid+1, cPtr=first;
int total=last-first+1, loop;
bool doneA = false, doneB = false;
apvector<int> c(a.length());
for (loop=1; loop<=total; loop++)
{
if (doneA)
{
c[cPtr] = a[bPtr];
bPtr++;
}
else
if (doneB)
{
c[cPtr] = a[aPtr];
aPtr++;
}
else// ok to compare, valid data in each sublist
if (a[aPtr] < a[bPtr])
{
c[cPtr] = a[aPtr];
aPtr++;
}
else
{
c[cPtr] = a[bPtr];
bPtr++;
}
cPtr++;
if (aPtr > mid) doneA = true;
if (bPtr > last) doneB = true;
}// for loop
for (loop=first; loop<=last; loop++)
a[loop] = c[loop];
}
void quickSort (apvector<int> &list, int first, int last)
{
int g = first, h = last;
	int midIndex, dividingValue;
	midIndex = (first + last) / 2;
	dividingValue = list[midIndex];
	do
	{
		while (list[g] < dividingValue) g++;
		while (list[h] > dividingValue) h--;
		if (g <= h)
		{
			swap(list[g], list[h]);
			g++;
			h--;
		}
	}
	while (g < h);
	if (h > first) quickSort (list,first,h);
	if (g < last) quickSort (list,g,last);
}
void sortMenu (apvector<int> &nums)
{
char choice;
apstring junk; // used to pick up endl, then ignore it
fillArray(nums);
apvector<int> holdOriginal(nums);// want to use the original unsorted
// vector each time we sort and count
SysTimer clock;
do
{
cout << "Sorting algorithm menu" << endl << endl;
cout << "(1) Selection sort" << endl;
cout << "(2) Insertion sort" << endl;
cout << "(3) Recursive mergesort" << endl;
cout << "(4) Quicksort" << endl;
cout << "(5) Print Vector" << endl;
cout << "(6) Quit" << endl << endl;
cout << "Choice ---> ";
cin >> choice;
getline(cin, junk); // dump endl
if (choice != '5')
nums = holdOriginal;// reset vector so we can again sort the same original unsorted data
if ('1'<=choice && choice<='5')
{
	clock.start();
// START YOUR TIMER HERE (figure out and use systimer class)
switch (choice)
{
case '1' : selectionSort(nums); break;
case '2' : cout << endl << "INSERTION_SORT" << endl << endl;
insertionSort(nums); break;
case '3' : cout << endl << "MERGE_SORT" << endl << endl;
mergeSort(nums, 0, nums.length()-1); break;
case '4' : cout << endl << "QUICK_SORT" << endl << endl;
quickSort(nums, 0, nums.length()-1); break;
case '5' : screenOutput(nums); break;
}
// STOP YOUR TIMER HERE and print elapsed time with appropriate message
// but don't print time if option 5 was chosen
clock.stop();
if( choice >='1' && choice<='4' )
	cout << clock.elapsedTime();
clock.reset();
		
cout << "\n\nPress ENTER To go on ...";
getline(cin, junk);
clrscr();
}
else if (choice != '6')
{
clrscr();
cout << "Can you read? Try Again!\n";
}
}
while (choice != '6');
}


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments
4/24/2002 4:13:00 AMPRIDDY

PRIDDY nice codes, but sorry, just a lil smartA** about the swap function, for strings in the "=" operator will not make the swaping.
(If this comment was disrespectful, please report it.)

 
10/6/2002 12:23:39 AM

where to get the extra .h files.........

(If this comment was disrespectful, please report it.)

 
11/7/2002 5:39:44 PM

I need to SysTimer.h. Where can I get it?
(If this comment was disrespectful, please report it.)

 
5/4/2003 7:27:24 AM

I can't fine header files. where can ý get it
(If this comment was disrespectful, please report it.)

 
7/15/2003 2:28:01 AM

why cant i run the system? There are some errors occuring. Please help especially the sysTimer.h
(If this comment was disrespectful, please report it.)

 
11/8/2003 8:40:30 PMMike Banwell

Can I get a version with comments?
(If this comment was disrespectful, please report it.)

 
5/22/2007 5:45:07 AMBADSHA

void ins_a(int a[], int s)


{
int a1[30];
a1[0] = a[0];
for (int i = 1; i < s; i++)


{
int temp = a[i];
int j = i - 1;
while (( a1[j] > temp) && (j>=0))


{
a1[j+1] = a[j];
j--;
}
a1[j+1] = temp;
}
for (int k = 0; k < s; k++)
{
a[k] = a1[k];
}


}

THIS WAS MT CODING FOR INSERTION SORT , COULD PLEASE TEL ME WHERE I WENT WRONG
(If this comment was disrespectful, please report it.)

 
6/15/2007 2:17:34 AMlalit gupta

hi

(If this comment was disrespectful, please report it.)

 
3/8/2011 6:26:11 AMyna

when the program is execute.. its wrong .. why ? :(
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.