[Dev-C++] Problem with example from Savitch book
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Opacki, J. <Jos...@ng...> - 2003-10-16 13:38:52
|
Hello All,
I'm working on building a generic sort function with templates that I got
out of Walter Savitch's book "Problem Solving with C++". My error is this
that it is not sorting correctly for me. I think I have just been staring
at it for too long. Can someone take a peak and tell me of my obvious
mistake. Thanks.
Joe
---------------------
// sorting function using templates
#include <iostream>
#include <cstdlib>
using namespace std;
template<class T>
void swapValues(T& var1, T& var2)
{
T temp;
temp = var1;
var1 = var2;
var2 = temp;
}
template<class BaseType>
int indexOfSmallest(const BaseType a[], int startIndex, int numberUsed)
{
BaseType min = a[startIndex];
int indexOfMin = startIndex;
for (int index = startIndex + 1; index < numberUsed; index++)
{
if (a[index] < min)
{
min = a[index] < min;
indexOfMin = index;
// min is the smallest of a[startIndex] through a[index]
}
}
return indexOfMin;
}
template<class BaseType>
void sort(BaseType a[], int numberUsed)
{
int indexNextSmallest;
for(int index = 0; index < numberUsed - 1; index++)
{
// place the correct value in a[index]
indexNextSmallest = indexOfSmallest(a, index, numberUsed);
swapValues(a[index], a[indexNextSmallest]);
// a[0] <= a[1] ... <= a[index] are the smallest of the original array
// elements. The rest of the elements are in the remaining positions
}
}
int main()
{
int i;
// sorting integers
int a[10] = {9, 8, 3, 1, 5, 2, 1, 7, 3, 9};
cout << "Unsorted integers: " << endl;
for (i = 0; i < 10; i++)
{
cout << a[i] << " ";
}
cout << endl;
sort(a, 10);
cout << "In sorted order: " << endl;
for (i = 0; i < 10; i++)
{
cout << a[i] << " ";
}
cout << endl;
// sorting doubles
double b[10] = {9.3, 8.8, 3.32, 1.21, 5.36, 2.45, 1.11, 7.3, 3.96,
9.36};
cout << "Unsorted doubles: " << endl;
for (i = 0; i < 10; i++)
{
cout << b[i] << " ";
}
cout << endl;
sort(b, 10);
cout << "In sorted order: " << endl;
for (i = 0; i < 10; i++)
{
cout << b[i] << " ";
}
cout << endl;
// sorting chars
char c[10] = {'G', 'Z', 'M', 'A', 'R', 'N', 'B', 'W', 'C', 'D'};
cout << "Unsorted chars: " << endl;
for (i = 0; i < 10; i++)
{
cout << c[i] << " ";
}
cout << endl;
sort(c, 10);
cout << "In sorted order: " << endl;
for (i = 0; i < 10; i++)
{
cout << c[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
|