2015-01-14 7 views
1

내 첫 번째 프로그래밍 랩에서는 정렬 알고리즘을 수행하여 문자 배열을 정렬합니다. 두 개의 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이야?

답변

2

이 작업을 시도 할 수 있습니다 : 당신은 동등한 while 루프로 for 루프 중 하나를 대체 할 수

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

내부 3 행은 std :: swap처럼 보입니다.) – CoryKramer

0

.

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

을 변환하도록 선택하는 경우 for 루프 같은 :

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

이 있습니다 for (a; b; c) d 같은 코드와 거의 동일합니다 약간 사소한 차이점이 있습니다. 그러나 다루고있는 종류의 문제에 대해서는 아마 관련이 없습니다.

관련 문제