欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

算法之简单排序和冒泡排序

程序员文章站 2024-03-16 14:13:28
...
package PracticeTest;

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

public class Sort {

	/**
	 * @2018.08.13
	 * 算法之简单排序和冒泡排序
	 */
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入随机数组大小len:");
		int len = scanner.nextInt();
		System.out.println("请输入随机数组范围max:");
		int max = scanner.nextInt();
		System.out.println("");
		SelectSort(len,max);
		System.out.println("");//仅为了换行,清晰
		MaoPaoPaiXu(len,max);//降序
		System.out.println("");
		MaoPaoPaiXu1(len,max);//升序
		System.out.println("");
	}
	
	public static int[]  RandomArray(int len,int max){
		int arr[] = new int[len];
		for(int i = 0;i<arr.length;i++){
			arr[i] = (int)(Math.random()*max);
		}
		System.out.println("原arr = " + Arrays.toString(arr));
	    return arr;
	}
	
	//简单排序算法
	public static int SelectSort(int len,int max){
		int arr[] = RandomArray(len,max);
		int min;
		for(int i = 0;i<arr.length -1;i++){
			for(int j =0;j<arr.length-1-i;j++){
				if(arr[j]>arr[j+1]){
					min = arr[j+1];
					arr[j+1] = arr[j];
					arr[j] = min;
				}
			}
		}
		System.out.println("arr简单排序后结果为:");
		System.out.println("arr = " + Arrays.toString(arr));
		return 0;
	}
	
	public static int MaoPaoPaiXu(int len,int max){
		int arr[] = RandomArray(len, max);
		//冒泡排序,降序
		for(int i = 0;i<arr.length-1;i++){
			for(int j = 0;j <arr.length-1-i;j++){
				if(arr[j]<arr[j+1]){
					int t = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = t;
				}
			}
		}
		System.out.println("arr冒泡排序降序后结果为:");
		System.out.println("arr = " + Arrays.toString(arr));
		return 0;
	}
	
	public static void MaoPaoPaiXu1(int len,int max){
		int arr[] = RandomArray(len, max);
		//冒泡排序,升序
		for (int k = 0; k < arr.length -1; k++) {
			for (int j = 0; j < arr.length - 1 - k; j++) {
				if (arr[j] > arr[j+1]) {
					int a = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = a;
				}
			}
		}
		System.out.println("arr冒泡排序升序后结果为:");
		System.out.println("arr = " + Arrays.toString(arr));
		return ;
	}
	
}

 

 

算法之简单排序和冒泡排序
运行结果
相关标签: java a