삽입정렬 compare 직접 만들어서 해보기
#include <iostream>
using namespace std;
struct Node
{
int a, b;
};
Node arr[5] = {{4, 2}, {5, 3}, {5, 9}, {4, 1}, {3, 7}};
bool compare(Node a, Node b)
{
if(a.a > b.a)
return false;
if(a.a == b.a)
{
if(a.b < b.b)
return false;
}
return true;
}
int main()
{
for(int i=0; i<5; i++)
{
for(int j=i; j>0; j--)
{
if(compare(arr[j-1], arr[j]) == false)
{
swap(arr[j], arr[j-1]);
}
else
break;
}
}
for(int i=0; i<5; i++)
cout << arr[i].a << ' ' << arr[i].b << '\n';
return 0;
}
1. 짝수우선
2. 작은 수 우선
#include <iostream>
#include <algorithm>
using namespace std;
int arr[6] = {4, 2, 5, 1, 7, 9};
bool compare(int a, int b)
{
if(a % 2 == 0 && b % 2 == 1)
return true;
if(a % 2 == 1 && b % 2 == 0)
return false;
return a < b;
}
int main()
{
sort(arr, arr+6, compare);
for(int i=0; i<6; i++)
cout << arr[i] << ' ';
return 0;
}
1. ABC가 아닌 알파벳 우선
2. 내림차순
#include <iostream>
#include <string>
using namespace std;
bool compare(char a, char b)
{
if(a > 'C' && b < 'D') return true;
if(a < 'D' && b > 'C') return false;
return a > b;
}
int main()
{
string words = "ABTRASK";
sort(words.begin(), words.end(), compare);
for(int i=0; i<words.length(); i++)
cout << words[i] << ' ';
return 0;
}
1. 큰수 우선
2. 알파벳 빠른거 우선
#include <iostream>
using namespace std;
struct Node
{
int a;
char b;
};
Node arr[5] = {{5, 'A'}, {7, 'B'}, {5, 'Q'}, {7, 'A'}, {5, 'C'}};
bool compare(Node a, Node b)
{
if(a.a == b.a)
return a.b < b.b;
return a.a > b.a;
}
int main()
{
sort(arr, arr+5, compare);
for(int i=0; i<5; i++)
cout << arr[i].a << ' ' << arr[i].b << '\n';
return 0;
}
'C++ > 공부 정리' 카테고리의 다른 글
재귀, 배열 원상복귀, (0) | 2022.04.22 |
---|---|
순열, 조합 (0) | 2022.04.21 |
슬라이딩 윈도우 (0) | 2022.04.08 |
파싱 - split 함수 작성, replace 함수 작성 (0) | 2022.03.16 |
무방향 그래프 싸이클 확인 (0) | 2022.03.09 |