C & C++/HackerRank
[HackerRank] Running Time of Algorithms
와금
2021. 9. 19. 18:13
728x90
https://www.hackerrank.com/challenges/runningtime/problem
Running Time of Algorithms | HackerRank
The running time of Algorithms in general and Insertion Sort in particular.
www.hackerrank.com
Algorithms > Sorting
배열이 주어지면 해당 배열을 정렬하여
shift 횟수를 리턴한다.
코드
int runningTime(int arr_count, int* arr) {
int *temp = arr;
int val, res = 0;
for(int i = 1; i < arr_count; i++){
val = temp[i];
int j = i - 1;
for(; j >= 0 && val < temp[j]; j--){
temp[j + 1] = temp[j];
res++;
}
temp[j+1] = val;
}
return res;
}
설명
주어진 배열을 임시로 저장할 동적 배열 temp를 선언하고,
배열의 원소를 임시로 저장할 val 변수, shift 횟수를 저장할 res 변수를 선언한다.
for문을 돌면서 배열을 정렬하고, shift가 이루어질 때마다 res를 1 증가시킨다.
모든 과정이 끝나면 res(shift 횟수)를 리턴한다.
728x90