728x90
옆의 값과 비교하여 더 큰 값을 오른쪽과 바꾼다.
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
int temp;
int array[10] = {2,4,1,3,5,6,7,8,9,10};
for (int i = 0; i<10; i++) {
for (int j = 0; j<9-i; j++) {
// 9-i 인 이유는 뒤에서 부터 배열을 하나씩 감소시키면서 진행되기 때문이다.
if (array[j]>array[j+1]) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (int i = 0; i<10; i++) {
cout << array[i] << " ";
}
return 0;
}
728x90