7-1字符串的冒泡排序

it2022-05-05  125

Java:

import java.util.Scanner; public class S7_01 { static int n, k; static String[] str = new String[105]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); k = sc.nextInt(); for (int i = 0; i < n; i++) { str[i] = sc.next(); } f(); } static void f() { for (int i = n; i > n - k; i--) { for (int j = 0; j < i - 1; j++) { if (str[j].compareTo(str[j + 1]) > 0) exchange(j, j + 1); } } for (int i = 0; i < n; i++) { System.out.println(str[i]); } } static void exchange(int a, int b) { String tem = str[a]; str[a] = str[b]; str[b] = tem; } }

C++

#include<iostream> #include<string> using namespace std; string str[105]; int main(){ int n,k; cin>>n>>k; for(int i=0;i<n;i++){ cin>>str[i]; } string st; for(int i=0;i<k;i++){ for(int j=0;j<n-1;j++){ if(str[j]>str[j+1]){ st=str[j]; str[j]=str[j+1]; str[j+1]=st; } } } for(int i=0;i<n;i++){ cout<<str[i]<<endl; } return 0; }

最新回复(0)