java 实现排序

1package com.hsm.mySort; 2 3import java.util.Random; 4 5/** 6 * 排序 7 * @author steven 8 * 9 */ 10public class MySort { 11 public static void main(String[] args) { 12 Random rd=new Random(); 13 int a[]=new int[100]; 14 for(int i=0;i<100;i++){ 15 a[i]=rd.nextInt(1000); 16 } 17 //bubbleSort(a); 18 //insertSort(a); 19 //shellSort(a); 20 selectSort(a); 21 } 22 /** 23 * 冒泡排序 24 * @param a 25 */ 26 static void bubbleSort(int [] a){ 27 int temp=0;//临时交换 28 for(int i=0;i<a.length;i++){//遍历 29 boolean flag=false;//标识有没有交换 30 for(int j=i+1;j<a.length;j++){ 31 if(a[i]>a[j]){ 32 temp=a[i]; 33 a[i]=a[j]; 34 a[j]=temp; 35 flag=true; 36 } 37 } 38 if(flag) break;//没有交换元素表明已经是有序的了 39 } 40 for (int i : a) {//输出排好序的元素 41 System.out.println(i); 42 } 43 } 44 /** 45 * 插入排序 46 * @param a 47 */ 48 static void insertSort(int [] a){ 49 int temp=0;//临时交换 50 int j=0; 51 for(int i=1;i<a.length;i++){//遍历 52 temp=a[i]; 53 for(j=i;j>0&&a[j-1]>temp;j--){//将元素往后移 54 a[j]=a[j-1]; 55 } 56 a[j]=temp;//将元素插入到正确的位置 57 } 58 for (int i : a) {//输出排好序的元素 59 System.out.println(i); 60 } 61 } 62 /** 63 * 希尔排序 64 * @param a 65 */ 66 static void shellSort(int [] a){ 67 int temp=0; 68 int j; 69 for(int d=a.length/2;d>0;d/=2){//间隔每次为原来的1/2 70 for(int i=0;i<a.length/d;i++){//这个地方其实就是插入排序 71 temp=a[i]; 72 for(j=i;j>=d&&a[j-d]>temp;j-=d){//将元素往后移 73 a[j]=a[j-d]; 74 } 75 a[j]=temp;//将元素插入到正确的位置 76 } 77 } 78 for (int i : a) {//输出排好序的元素 79 System.out.println(i); 80 } 81 } 82 /** 83 * 选择排序 84 * @param a 85 */ 86 static void selectSort(int [] a){ 87 int temp=0;//记录最小值的位置 88 int temp2=0; 89 for(int i=0;i<a.length;i++){//遍历 90 boolean flag=false;//标识有没有交换 91 for(int j=i;j<a.length;j++){ 92 if(a[j]<a[temp]){ 93 temp=j; 94 } 95 } 96 if(flag) break;//没有交换元素表明已经是有序的了 97 temp2=a[i]; 98 a[i]=a[temp]; 99 a[temp]=temp2; 100 } 101 for (int i : a) {//输出排好序的元素 102 System.out.println(i); 103 } 104 } 105}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Java实现排序算法

//冒泡排序publicstaticvoidbubbleSort(intdata){intndata.length;for(inti0;i<n;i){for(intj0;j<n;j){if(

Java比较器

前言本篇文章主要介绍的是Java比较器的实现与测试。1.java.lang.Comparable排序接口定义:Comparable是排序接口。若一个类实现了Comparable接口,就意味着该类支持排序。实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或Arrays