Strings in Alphabetical order?
Jan 26, 2010 at 12:00am UTC
I'm not sure how to program things to appear in alphabetical order.
Jan 26, 2010 at 12:46am UTC
Generally you get a vector or some other container of stuff, and then sort it according to however you want it to appear.
Jan 26, 2010 at 2:39am UTC
There is a algorithm sort in the STL library. However it's best to write your own so you understand how all the different sorts work.
typical bubble sort: Bubble is a little more complicated than insertion or selection sorts so you should look up how to do insertion and selection, both of which can be found on wikipedia
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
using namespace std;
void bubbleSort(int [], int );
int main ()
{
int y = 0;
int myarray[10] = { 9, 3, 6, 1, 4, 8, 7, 2, 10, 5 };
bubbleSort(myarray, 10);
for (int i=0; i<10; i++)
cout << myarray[i] << endl;
return 0;
}
void bubbleSort(int arr[], int n)
{
bool swapped = true ;
int j = 0;
int tmp;
while (swapped)
{
swapped = false ;
j++;
for (int i = 0; i < n - j; i++)
{
if (arr[i] > arr[i + 1])
{
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
swapped = true ;
}
}
}
}
Last edited on Jan 26, 2010 at 2:41am UTC
Jan 26, 2010 at 3:21am UTC
a string version of gcampton's bubble sort..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <iostream>
#include <string>
using namespace std;
void bubbleSort(string[], int );
int main ()
{
int y = 0;
string myarray[6] = { "orange" , "apple" , "mango" , "lemon" , "guava" , "strawberry" };
bubbleSort(myarray, 6);
for (int i=0; i<6; i++)
cout << myarray[i] << endl;
return 0;
}
void bubbleSort(string arr[], int n)
{
bool swapped = true ;
int j = 0;
string tmp;
while (swapped)
{
swapped = false ;
j++;
for (int i = 0; i < n - j; i++)
{
if ( arr[i].compare(arr[i + 1]) )
{
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
swapped = true ;
}
}
}
}
Topic archived. No new replies allowed.