C, C++
String 함수의 사용, 선택정렬- 버블정렬
SuuuuuuuL
2018. 12. 18. 10:35
#include <stdio.h>
#include <string.h> // string 함수 사용 가능하게 하기 위해서
// selection sort
void sort(char (*word)[20], int len){
char temp[20];
for(int i = 0; i < len-1; i++){
for(int t = i+1; t < len; t++){
int check = strcmp(word[i],word[t]);
if(check>0){ // 교환
strcpy(temp, word[i]); // temp에다 i넣기
strcpy(word[i],word[t]); // i에다 t 넣기
strcpy(word[t],temp); // t에다 i(temp) 넣기
//printf("%d:%s, %d:%s\n",i,word[i],t,word[t]);
}
}
}
}
void bubbleSort(char (*word)[20], int len){
char temp[20];
for(int i = len-1; i >0; i--){// 비교 횟수 맨 뒤부터 정렬되니까 비교할 수는 점점 줄어야 함
for(int t = 0; t < i; t++){
int check = strcmp(word[t],word[t+1]); // 옆의 수와 비교
if(check>0){ //
strcpy(temp, word[t]); // temp에다 t넣기
strcpy(word[t],word[t+1]); // t에다 t+1 넣기
strcpy(word[t+1],temp); // t+1에다 t(temp) 넣기
}
}
}
}
int main(){
char str1[50]= "banana";
char str2[50]= "apple";
char word[5][20] = {"strawberry","apple","cat","brown","book"};
int len= sizeof(word)/sizeof(word[0]);
for(int i = 0; i < len; i++){
printf("%s\n", word[i]);
}
sort(word,len);
//printf("len: %d \n", len);
for(int i = 0; i < len; i++){
printf("%s\n", word[i]);
}
//printf("%d\n", strlen(str1));
//printf("%d\n", strcmp(str1, str2))
}
String 함수
strlen : 문자열의 길이를 반환
strcmp(a,b) : 문자열을 비교하여 a>b면 1, a==b면 0 , a<b 면 -1을 리턴
strcpy(target, copy) : copy를 target으로 복사
아래는 함수의 구현
int mystrcmp(char* w1, char* w2){
// 작은 거 기준으로...
int i=0;
while(1){
if(w1[i] < w2[i]){
return -1;
}
if(w1[i] > w2[i]){
return 1;
}
i++;
}
return 0;
}
int mystrlen(char* word){
int count = 0;
while(1){
if(word[count++]!=0){ //'\0'이어도 괜찮음
}else{
return count-1; // null 값 카운팅 제외
}
}
}
int mystrcpy(char* word, char* buffer){
int i=0;
while(1){
if(word[i]!=0){
buffer[i] = word[i];
}else{
buffer[i] = word[i]; // 끝값 0을 하나 넣어주고 끝내자!
return i;
break;
}
i++;
}
}