堆排序,选择排序,冒泡排序

堆排序,选择排序,冒泡排序的三种排序

package experiment;

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

public class experiment_02 {
//堆排序
//使堆母结点大于两个子节点
public static void heapify(int a[],int n,int i) {
int c1 = 2 * i + 1;//子节点1
int c2 = 2 * i + 2;//子节点2
int max = i;
//比较母结点与两个子节点的大小
if(c1 < n && a[c1] > a[max]) {
max = i;
}
if(c2 < n && a[c2] > a[max]) {
max = i;
}
if(max!=i) {
//若max改变进行交换
swap(a,max,i);
//对其子节点继续进行 使母结点大于两个子节点 递归试其最终整个堆符合
heapify(a,n,max);
}
}
//建堆
public static void heap_build(int[] a,int n) {
int last_node = n-1;
int parent = (last_node - 1)/2;
int i ;
for(i = parent;i >= 0;i–) {
heapify(a,n,i);
}
}
//进行堆排序
public static void heap(int[] a,int n) {
heap_build(a,n);
for(int i = n-1;i >= 0;i–) {
swap(a,i,0);
heapify(a,i,0);
}
System.out.println(“堆排序后为”+Arrays.toString(a));
}
// //冒泡排序(两两进行比较)
// public static void bubble(int a[],int n) {
// for(int j = 0;j < n-1;j++) {
// if(j == (n-1)) {
// break;
// }
// for(int t = 0;t<n-1-j;t++) {
// if(a[t] > a[t+1]) {
// int temp = a[t];
// a[t] = a[t+1];
// a[t+1] = temp;
// }
//
// }
// }
// System.out.println(“冒泡排序后为”+Arrays.toString(a));
// }
选择排序(从无序数组中选出最小元素 然后不断循环)
// public static void select(int[] a,int n) {
// for(int q = 0;q<n-1;q++) {
// int index = q;
// int e;
// for(e = q+1;e<n;e++) {
// if(a[e]<a[index]) {
// index = e;
// }
// }
// int temp = a[index];
// a[index] = a[q];
// a[q] = temp;
// }
// System.out.println(“选择排序后为”+Arrays.toString(a));
// }
public static void swap(int a[],int b,int c) {
int d = a[b];
a[b] = a[c];
a[c] = d;
}
public static void main(String[] args) throws Exception {
System.out.println(“请输入排序总数”);
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] a = new int[n];
for(int i = 0;i<n;i++) {
a[i] = s.nextInt();
}
System.out.println(“无序数组为”+Arrays.toString(a));
// bubble(a,n);
// select(a,n);
heap(a,n);
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值