CTRLee
CTRLee

Reputation: 21

Sorting using a while loop and a for loop?

My first programming lab is to do a sorting algorithm to sort a character array. I've successfully do it using two for loops, but in order to improve my skills, I want to know if there's a way to do it using a while loop and a for loop?

//Include any needed libraries
 #include <iostream>
 #include <algorithm>
 #include <iterator>

//Specify the standard namespace
using namespace std;

int main(){
//Initializes variables.

char foo[7] = {'a','c','g','j','a','c','d'};
//char foo[7];
bool sorted =false;
int i = 0;
int j = 0;
char temp;

//Print out the pre-sorting array. 
cout << "The array before sorting is: ";
for (int i=0; i<7; i++){
    cout << foo[i];
}
cout << endl;



//The swap function. 
    for(i=0;i<7;i++){
        for (j=0; j<7;j++){
            if(foo[i]<foo[j]){
                temp = foo[i];              
                foo[i] = foo[j];
                foo[j] = temp;
            }
        }
    }
}

cout << "The array after sorting is: ";
for (int i=0; i<7; i++){
    cout << foo[i];
}

cout << endl;


return 0;
} 

EDIT: Here's a psuedocode written by our TA:

array[];
bool sorted = false;
while(!sorted){
   sorted = true;
   for each element{
      compare
      swap
   if swapped: sorted = false
}

So what I really wanted to know is how to I integrate boolean statements in the while loop?

Upvotes: 1

Views: 13554

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490328

In general, a for loop like: for (a; b; c) d is nearly equivalent to code like:

a;
while (b) {
    d;
    c;
}

There are a few minor differences, but for the kind of thing you're dealing with, they're probably irrelevant.

Upvotes: 2

ravi
ravi

Reputation: 10733

You can replace either of the for loops with equivalent while loop.

for(i=0;i<7;i++)
{
    j = 0;
    while( j<7)
    {
        if(foo[i]<foo[j])
        {
            temp = foo[i];              
            foo[i] = foo[j];
            foo[j] = temp;
        }
      j++
    }
}

OR if you choose to convert outer loop, then

int i = 0;
while (i < 7)
{
  for (j = 0; j < 7; j++)
  {
      if(foo[i] < foo[j])
      {
          temp = foo[i];              
          foo[i] = foo[j];
          foo[j] = temp;
      }
   }
   i++;
 }

Upvotes: 0

Lawrence Aiello
Lawrence Aiello

Reputation: 4638

You can try this:

int i = 0;
while (i < 7)
{
    for (j = 0; j < 7; j++)
    {
        if(foo[i] < foo[j])
        {
            temp = foo[i];              
            foo[i] = foo[j];
            foo[j] = temp;
        }
     }
i++;
}

Upvotes: 2

Related Questions