티스토리 뷰

자료구조

선택정렬 구현 연습

심재철 2018. 8. 9. 21:04
#include <iostream>
using namespace std;

void swap(int * arr,int a,int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}

int findindex(int* arr,int left,int right){
int minindex = left;
for(int i=minindex+1; i<right; i++){
if(arr[i]<arr[minindex])
minindex = i;
}
return minindex;
}

//배열 스캔 후 최소값 찾은다음에 맨앞 이랑 교환, 맨앞은 점점 증가되다가 마지막까지감
int selectionsort(int* arr,int left,int right){
for(int i=left; i<right; i++){
int index = findindex(arr,i,right);
swap(arr,i,index);
}
}

int main(){
int arr[] = {2,2,4,5,1,55,2,4,5,29,4,0,-1};
selectionsort(arr,0,13);
for(int k : arr)
cout<<k<<" ";
cout<<endl;

}

좀 더 간략화 된 방법


#include <iostream>
using namespace std;

void selectionsort(int* arr,int left,int right){
for(int i=left; i<right; i++){
int minindex = i;
for(int j=i+1; j<right; j++){
if(arr[minindex] > arr[j])
minindex = j;
}
//swap minindex and i
int temp = arr[minindex];
arr[minindex] = arr[i];
arr[i] = temp;
}
}

int main(){
int arr[] = {2,2,4,5,1,55,2,4,5,29,4,0,-1};
selectionsort(arr,0,13);
for(int k : arr)
cout<<k<<" ";
cout<<endl;

}


댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함