C++
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the countSwaps function below.
void countSwaps(vector<int> a) {
int count=0;
for(int i=0; i<a.size(); i++){
for(int j=0; j<a.size()-1; j++){
if(a[j]>a[j+1]) {
swap(a[j], a[j+1]);
count += 1;
}
}
}
cout << "Array is sorted in " << count << " swaps." << endl;
cout << "First Element: " << a.front() << endl;
cout << "Last Element: " << a.back() << endl;
}
int main()
{
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string a_temp_temp;
getline(cin, a_temp_temp);
vector<string> a_temp = split_string(a_temp_temp);
vector<int> a(n);
for (int i = 0; i < n; i++) {
int a_item = stoi(a_temp[i]);
a[i] = a_item;
}
countSwaps(a);
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
- swap이 발생하는 반복문 내 if문에서 swap 후 count를 증가시킨다.
- 이후 문제에서 출력하라는 swap 개수(count), 첫 번째 원소(a.front()), 마지막 원소(a.back())을 출력한다.
Python
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countSwaps function below.
def countSwaps(a):
count=0
for i in range(0,len(a)):
for j in range(0, len(a)-1):
if a[j] > a[j+1]:
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
count += 1
print("Array is sorted in "+str(count)+" swaps.")
print("First Element: "+str(a[0]))
print("Last Element: "+str(a[len(a)-1]))
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().rstrip().split()))
countSwaps(a)
- python의 경우 별도의 swap 함수가 없어서 직접 바꿔준다. 다른 부분은 C++과 동일