# 数列排序

### 数列排序

问题描述

5
8 3 6 4 9

3 4 6 8 9


#### 方法一：

import java.util.Scanner;

public class SequenceOfSorting {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int []arr = new int[n];
//往数组里添加元素
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
int temp = 0;
//排序
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]){
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
//打印数组
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}


#### 方法二：

import java.util.Scanner;

public class SequenceOfSorting2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int []arr = new int[n];

for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

for (int i = 0; i < n; i++) {
for (int j = i;j > 0;j--){
if (arr[j - 1] > arr[j]){
int temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}

for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}


#### 方法三：

import java.util.Scanner;

public class SequenceOfSorting3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int []arr = new int[n];

for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

for (int i = 0; i < n; i++) {
int temp = i;
for (int j = i;j < n;j++){
if (arr[j] < arr[temp]){ // 将数组里最小元素的下标赋值给temp
temp = j;
}
}
int temp1 = arr[i];
arr[i] = arr[temp];
arr[temp] = temp1;
}

for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}


#### 方法四：

import java.util.Arrays;
import java.util.Scanner;

public class SequenceOfSorting {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();
int []arr = new int[n];
//往数组里添加元素
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
Arrays.sort(arr);//排序

//遍历输出数组数据
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}

posted @ 2021-07-21 17:13  小芦荟同学  阅读(52)  评论(0编辑  收藏  举报