Day 20: Sorting
生活随笔
收集整理的這篇文章主要介紹了
Day 20: Sorting
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目:
?
?
C++:
#include <stdio.h> #include <stdlib.h> #include <vector> #include <map> #include <string> #include <exception> #include <stdexcept> #include <algorithm> #include <stack> #include <queue> #include <math.h> #include <iostream>using namespace std; int main() {int n;cin >> n;vector<int> a(n); //聲明動態(tài)數(shù)組for (int a_i = 0; a_i < n; a_i++) {cin >> a[a_i];}// Write Your Code Hereint numSwaps = 0;for (int i = 0; i < n; i++) {for (int j = 0; j < n-1; j++) {if (a[j] > a[j + 1]) {swap(a[j],a[j+1]); //使用swap()函數(shù),交換兩個變量numSwaps++;}}}cout << "Array is sorted in "<< numSwaps <<" swaps." << endl;cout << "First Element: " << a[0] << endl;cout << "Last Element: " << a[n - 1] << endl;system("pause");return 0; }python:
#!/bin/python3 #coding:utf-8import sysn = int(input().strip()) a = list(map(int, input().strip().split(' '))) # Write Your Code Here numSwaps=0 for i in range(a.__len__()):for j in range(a.__len__()-1):if a[j]>a[j+1]:temp=a[j]a[j] = a[j + 1]a[j+1]=tempnumSwaps+=1print("Array is sorted in",numSwaps,"swaps.") print("First Element:",a[0]) print("Last Element:",a[n-1])總結(jié):
C++:
使用vector聲明動態(tài)數(shù)組:
int n; cin >> n; vector<int> a(n); for (int a_i = 0; a_i < n; a_i++) {cin >> a[a_i]; }swap()交換函數(shù):
swap(a[j],a[j+1]);python:
輸入數(shù)據(jù),將其轉(zhuǎn)換為整型:
n = int(input().strip())將輸入的數(shù)據(jù),以空格分開,轉(zhuǎn)換為數(shù)組:
a = list(map(int, input().strip().split(' ')))list數(shù)組的長度:
a.__len__()python不支持n++這種寫法。
???? 因此,正確的自增操作應(yīng)該 n = n + 1 或者 n += 1。
?
參考:https://www.cnblogs.com/mlgjb/p/7866941.html
總結(jié)
以上是生活随笔為你收集整理的Day 20: Sorting的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 聚类分析在用户行为中的实例_网站用户行为
- 下一篇: 过去的 2017 年