使用 while 循环和 for 循环进行排序
Sorting using a while loop and a for loop?
我的第一个编程实验室是做一个排序算法来对字符数组进行排序。我已经成功地使用两个 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++;
}
相关文章:
- 气泡排序未正确循环
- C++ - 如何保持半随机数组在循环中排序
- 按升序对数组进行排序嵌套循环问题
- 如何并行化矩阵排序以进行循环
- 气泡排序循环,将一个数字更改为 0
- 选择排序 - 循环过早停止
- 尝试对字符串数组进行排序,但我似乎陷入了循环
- 循环中对向量进行排序
- 在 for 循环中重新排序测试条件:编译器错误?
- 单排序链表-无限循环
- 如何在不使用循环的情况下进行排序
- 提高循环缓冲区或堆排序性能
- 创建一个C++预排序迭代器,为循环提供树节点
- 使用 while 循环和 for 循环进行排序
- 计数排序无限循环
- 计数排序卡在 for 循环中
- 有什么更有效的方法来确保我不会在这个快速排序函数中陷入无限循环?(C++)
- 将"for"循环更改为单个"for"循环(排序)
- Qt foreach循环排序与QList的for循环排序
- 使用if循环排序时出现意外结果-糟糕的算法