Hello im creating a template class function of selection sort i wanted to know how i can change the code so that it could work for both arrays of integers and strings,right now it only works for strings code is below when i input numbers with only integers but when i input strings i get an error.
#include <iostream>
#include "Sort_Class.cpp"
#include <string>
using namespace std;
int main() {
int numbers[] = {8, 7, 2, 1};
const int NUMBERS_SIZE = 4;
int i = 0;
cout << "UNSORTED: " << endl;
for(i = 0; i < NUMBERS_SIZE; ++i) {
cout << numbers[i] << " ";
}
cout << endl;
Sort_Class::SelectionSort(numbers,NUMBERS_SIZE);
cout << "SORTED: ";
for(i = 0; i < NUMBERS_SIZE; ++i) {
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}
using namespace std;
#include <iostream>
#include <string>
class Sort_Class{
public:
template<typename TheType>
static void SelectionSort(TheType numbers[],int numbersSize);
//static void InsertionSort(TheType Numbers[], int numbersSize);
//static void Merge(TheType numbers[], int i,int j, int k);
//static void MergeSort(TheType numbers[], int i,int k);
};
template<typename TheType>
void Sort_Class::SelectionSort(TheType numbers[], int numbersSize) {
int i = 0;
int j=0;
int indexSmallest = 0;
int temp = 0;
for (i = 0; i < numbersSize - 1; ++i) {
// Find index of smallest remaining element
indexSmallest = i;
for (j = i + 1; j < numbersSize; ++j) {
if ( numbers[j] < numbers[indexSmallest] ) {
indexSmallest = j;
}
}
// Swap numbers[i] and numbers[indexSmallest]
temp = numbers[i];
numbers[i] = numbers[indexSmallest];
numbers[indexSmallest] = temp;
}
cout<< "Temp Selection Sort" << " " << endl << temp <<" " << endl << "Numbers[i]"<<" "<< endl << numbers[i]<<" "<< endl << "numbers[indexsmallest]"<< endl << numbers[indexSmallest]<<" "<< endl << "i"<<" "<<i<<" "<< endl << "J"<<" "<<j<<endl;
return;
}
Aucun commentaire:
Enregistrer un commentaire