java快速插入排序,java 实现插入排序冒泡排序快速排序

package com.cjy.concurrent;

public class Sort {

// 插入排序

public static void insertSort(int[] array) {

int[] result = new int[array.length + 1];

if (array != null && array.length > 0) {

result[0] = array[0];

}

for (int i = 1; i < array.length; i++) {

int flag = -1;

// 查找插入位置

for (int j = 0; j < result.length; j++) {

if (array[i] < result[j]) {

flag = j;

break;

}

}

if (flag == -1) {

// 没有找到直接放到位置i

result[i] = array[i];

} else {

// 找到插入位置,移动元素

for (int k = result.length - 1; k > flag; k--) {

result[k] = result[k - 1];

}

result[flag] = array[i];

}

}

// 打印输出

for (int m = 0; m < result.length - 1; m++) {

System.out.print(result[m] + " ");

}

System.out.print("\n");

}

// 冒泡排序

public static void bubbleSort(int[] array) {

int length = array.length;

for (int i = 0; i < array.length; i++) {

for (int j = 0; j < length - 1; j++) {

if (array[j] > array[j + 1]) {

int flag = array[j + 1];

array[j + 1] = array[j];

array[j] = flag;

}

}

length--;

}

// 打印输出

for (int m = 0; m < array.length; m++) {

System.out.print(array[m] + " ");

}

System.out.print("\n");

}

// 快速排序

public static void quickSort(int[] array, int begin, int end) {

if (begin < end) {

int p = position(array, begin, end);

quickSort(array, begin, p - 1);

quickSort(array, p + 1, end);

}

}

public static int position(int[] array, int begin, int end) {

int flag = array[begin];

int i = begin, j = end;

while (i < j) {

while (j > i && array[j] > flag) {

j--;

}

array[i] = array[j];

while (i < end && array[i] < flag) {

i++;

}

array[j] = array[i];

}

array[i] = flag;

return i;

}

public static void main(String[] args) {

int[] array1 = { 2, 4, 9, 3, 6, 7, 1, 5 };

int[] array2 = array1;

int[] array3 = array1;

insertSort(array1);

bubbleSort(array2);

quickSort(array3, 0, 7);

//打印输出

for (int m = 0; m < array3.length; m++) {

System.out.print(array3[m] + " ");

}

}

}

测试结果:

1   2   3   4   5   6   7   9

1   2   3   4   5   6   7   9

1   2   3   4   5   6   7   9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值