简单排序java(冒泡,选择,插入)

简单排序java(冒泡,选择,插入)

    • 冒泡
    • 选择
    • 插入
    • 测试

冒泡

package com.lexie.sort;

public class BubbleSort {
	public static void sort(long[] arr){
		long temp=0;
		for (int i = 0; i < arr.length-1; i++) {
			for (int j = arr.length-1; j >i; j--) {
				temp =arr[j];
				arr[j]=arr[j-1];
				arr[j-1]=temp;
			}
		}
	}
}

选择

package com.lexie.sort;

public class SelectionSort {
	public static void sort(long[] arr){
		int k=0;
		long temp=0;
		for (int i = 0; i < arr.length-1; i++) {
			k=i;
			for (int j = i; j<arr.length; j++) {
				if (arr[j]<arr[k]) {
					k=j;
				}
			}
			temp =arr[i];
			arr[i]=arr[k];
			arr[k]=temp;
		}
	}
}

插入

package com.lexie.sort;

public class InsertSort {
	public static void sort(long[] arr) {
		long temp = 0;
		for (int i = 1; i < arr.length; i++) {
			temp = arr[i];
			int j = i;
			while (j > 0 && arr[j - 1] > temp) {
				arr[j] = arr[j - 1];
				j--;
			}
			arr[j]=temp;
		}
	}
}

测试

package com.lexie.sort;

public class TestSort {
	public static void main(String[] args) {
		long[] arr = new long[5];
		arr[0] = 34;
		arr[1] = 23;
		arr[2] = 2;
		arr[3] = 1;
		arr[4] = -4;

		System.out.print("{");
		for (long num : arr) {
			System.out.print(num + " ");
		}
		System.out.print("}");
		System.out.println();

		/*
		 * BubbleSort.sort(arr);
		 * 
		 * System.out.println("冒泡排序后:");
		 * 
		 * System.out.print("{"); for (long num : arr) {
		 * System.out.print(num+" "); } System.out.print("}");
		 * System.out.println();
		 */

		/*
		 * SelectionSort.sort(arr);
		 * 
		 * System.out.println("选择排序后:");
		 * 
		 * System.out.print("{"); for (long num : arr) {
		 * System.out.print(num+" "); } System.out.print("}");
		 * System.out.println();
		 * 
		 * BubbleSort.sort(arr);
		 */
		InsertSort.sort(arr);
		System.out.println("插入排序后:");

		System.out.print("{");
		for (long num : arr) {
			System.out.print(num + " ");
		}
		System.out.print("}");
		System.out.println();

		BubbleSort.sort(arr);
	}
}

简单排序java(冒泡,选择,插入)_第1张图片

你可能感兴趣的:(数据结构,排序,数据结构,java,算法)