几种排序java实现


package com.wyh.anl;

public class TestSort{

/**
* @param args
*/
public static void main(String[] args) {

int a[] = { 115, 0, 5, 2, 1, 8, 9, 7, 6, 78 };
bublSort(a);
for (int j : a) {
System.out.print(j + " ");
}
}

// 插入排序
public static void insertSort(int a[]) {
for (int i = 1; i < a.length; i++) {
int tmp = a[i];
int j = i;

while (j > 0) {
if (tmp < a[j - 1]) {
a[j] = a[j - 1];
} else {
break;
}
j--;
}
a[j] = tmp;
}
}

// 选择排序
public static void selectSort(int a[]) {
for (int i = 0; i < a.length; i++) {
int sel = i;
int tmp = i;
for (int j = i; j < a.length; j++) {
if (a[tmp] > a[j]) {
tmp = j;
}
}
if (tmp != sel) {
int awp = a[sel];
a[sel] = a[tmp];
a[tmp] = awp;
}
}
}

// 冒泡排序法
public static void bublSort(int a[]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
int tmp = 0;
if (a[j] > a[j + 1]) {
tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
}
}

// 归迸排序法
public static void merageSort(int data[], int first, int n) {

int n1 = 0;
int n2 = 0;

if (n > 1) {
n1 = n / 2;
n2 = n - n1;

merageSort(data, first, n1);
merageSort(data, first + n1, n2);

merage(data, first, n1, n2);
}
}

private static void merage(int data[], int first, int n1, int n2) {

int tmp[] = new int[n1 + n2];

int serN1 = 0;
int serN2 = 0;
int serTmp = 0;

while (serN1 < n1 && serN2 < n2) {

if (data[first + serN1] < data[first + serN2 + n1]) {

tmp[serTmp++] = data[first + (serN1++)];

} else {

tmp[serTmp++] = data[first + n1 + (serN2++)];
}
}

while (serN1 < n1) {
tmp[serTmp++] = data[first + (serN1++)];
}

while (serN2 < n2) {
tmp[serTmp++] = data[first + n1 + (serN2++)];
}

for (int i = 0; i < (n1 + n2); i++) {
data[first + i] = tmp[i];
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值