使用 while 循环和 for 循环进行排序

Sorting using a while loop and a for loop?

本文关键字:循环 排序 while 使用 for      更新时间:2023-10-16

我的第一个编程实验室是做一个排序算法来对字符数组进行排序。我已经成功地使用两个 for 循环来做到这一点,但为了提高我的技能,我想知道是否有办法使用 while 循环和一个 for 循环来做到这一点?

//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;
} 

编辑:这是我们的TA编写的伪代码:

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

所以我真正想知道的是如何在 while 循环中集成布尔语句?

你可以试试这个:

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++;
}

一般来说,像这样的for循环: for (a; b; c) d几乎等同于以下代码:

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

有一些细微的差异,但对于您正在处理的那种事情,它们可能无关紧要。

您可以将任一for循环替换为等效的while循环。

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++
    }
}

或者,如果您选择转换外循环,则

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++;
 }