내 첫 번째 프로그래밍 랩에서는 정렬 알고리즘을 수행하여 문자 배열을 정렬합니다. 두 개의 for 루프를 사용하여 성공적으로 수행했지만 내 기술을 향상시키기 위해 while 루프와 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;
}
편집 :
이array[];
bool sorted = false;
while(!sorted){
sorted = true;
for each element{
compare
swap
if swapped: sorted = false
}
그래서 난 정말 알고 싶어 제가 while 루프에서 부울 문을 통합하는 방법입니다 : 여기에 우리의 TA가 쓴 psuedocode이야?
내부 3 행은 std :: swap처럼 보입니다.) – CoryKramer