Free2Code
The majority of forums are now only available as archives, which means posting/editing is disabled.

The Anything and Everything forum is still open.
 
Time: 2013-05-21, 05:58am
Sorts
Subject: Sorts  ·  Posted: 2006-12-04, 02:09pm
Rank: ? (1)
Member #: 29314
I have a slight bug in my code but I cant figure out what it is. I want to use a Bubble sort and and Insertion sort. I want to sort the names in deceding order using the bubble sort and then take the output from that and sort it in ascening order with the Insertion sort. Any help with what I'm doing wrong would be appreciated. Thanks!

#include <iostream>
#include <string>
using namespace std;

int main() {
char* words[4] = {"Chad", "Joe", "Trent", "Burt"};
char* hold;
int i, j;
////////////////////////////////////////////////////////////////

// BUBBLE SORT

//////////////////////////////////////////////////////////////

for(int i = 0; i < 4 - 1; i++)// For the outer loop
for(int j = 0;j < 4 - 1 - i;j++)// For the inner loop
{
if(strcmp(words[j], words[j + 1]) < 0)// Elements are out of order. Swap.
{
hold = words[j];
words[j] = words[j + 1];
words[j + 1] = hold;
}
}
for(int j = 0;j < 4;j++)
cout << words[j] ;// Prints out stuff sorted from Bubble Sort

///////////////////////////////////////////////////////////////////////

// Insertion Sort

//////////////////////////////////////////////////////////////////////


for(j = 1; j < 4; j++) {
hold = words[j];

for(i = j-1; i >= 0 && hold < words[i]; --i)
words[i+1] = words[i];
words[i + 1] = hold;
}
for(int j = 0;j < 4;j++)
cout << words[j]; // Prints out insertion sort result
}

 
  Reply to this ·  Post link ·  Top

Pages: 1

Please login or register to post a reply.

Penguino AVR

Want to learn about robotics or microcontrollers?
Check out the Penguino AVR from our friends at
Icy Labs