- 题目:
- 给定一个一维整型数组,自己实现冒泡排序、简单选择排序、快速排序完成对其的升序排列并输出?
- 答案
- 冒泡排序按降序排列
public class TestBubbleSort {
public static void main(String[] args) {
int[] arr={6,3,8,2,9,1};
System.out.println("排序前数组为:");
for(int num:arr){
System.out.print(num+" ");
}
for(int i=0;i<arr.length-1;i++){//外层循环控制排序趟数 ,最多循环array.length-1次
for(int j=0;j<arr.length-1-i;j++){//内层循环控制每一趟排序多少次 ,每趟最多比较arr.length-1-i次
if(arr[j]<arr[j+1]){
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
System.out.println();
System.out.println("排序后的数组为:");
for(int num:arr){
System.out.print(num+" ");
}
}
}
- 选择排序从前往后去顺序比较
public class TestSelectSort {
public static void selectSort(int[] numbers)
{
int size = numbers.length; //数组长度
int temp = 0 ; //中间变量
for(int i = 0 ; i < size-1 ; i++)
{
int k = i; //待确定的位置
//选择出应该在第i个位置的数
for(int j=i+1; j<=size-1; j++)
{
if(numbers[j] < numbers[k])
{
k = j;
}
}
//交换两个数
temp = numbers[i];
numbers[i] = numbers[k];
numbers[k] = temp;
}
}
public static void main(String[] args){
int[] noSortArray={9,38,2,22,88,10};
for(int old:noSortArray){
System.out.print(old+" ");
}
selectSort(noSortArray);
System.out.println();
for(int newVal:noSortArray){
System.out.print(newVal+" ");
}
}
}
- 快速排序
public class TestQuickSort
{
public static void quickSort(int[] intArray,int low,int high){
if(low>=high){
return;
}
int low_temp=low;
int high_temp=high;
int base=intArray[low_temp];
//约定执行条件
while(low<high){
//从右往左走,找到小于基准值的停下
while(low<high && intArray[high]>=base){
high--;
}
//从左往右走,找到大于基准值的停下
while(low<high && intArray[low]<=base){
low++;
}
//交换low和high值
if(low<high){
int temp=intArray[low];
intArray[low]=intArray[high];
intArray[high]=temp;
}
}
//交换low和基准值
if(low_temp!=low){
intArray[low_temp]=intArray[low];
intArray[low]=base;
}
//左右各自递归循环
quickSort(intArray,low_temp,low-1);
quickSort(intArray,low+1,high_temp);
}
public static void main(String[] args)
{
int[] intArray={10,7,2,4,9,8,3,8,9,1};
TestQuickSort.quickSort(intArray,0,intArray.length-1);
for(int temp:intArray){
System.out.print(temp+" ");
}
}
}
天亮教育是一家从事大数据云计算、人工智能、教育培训、产品开发、咨询服务、人才优选为一体的综合型互联网科技公司。
公司由一批BAT等一线互联网IT精英人士创建,
以"快乐工作,认真生活,打造IT职业技能教育的一面旗帜"为愿景,胸怀"让天下没有难找的工作"使命,
坚持"客户第一、诚信、激情、拥抱变化"的价值观,
全心全意为学员赋能提效,践行技术改变命运的初心。
更多学习讨论, 请加入
官方-天亮大数据交流-366784928
群二维码:
官方-天亮web前端交流-972788995
群二维码:
欢迎关注天亮教育公众号,大数据技术资料与课程、招生就业动态、教育资讯动态、创业历程分享一站式分享,官方微信公众号二维码:
天亮教育大数据官方群318971238,
天亮教育web前端官方群318971238,
爬虫、nlp技术qq群320349384
hadoop & spark & hive技术群297585251
教育培训官网:http://myhope365.com
项目研发业务尚云科技官网:http://shangyuninfo.com/
天亮教育公开课-从小白到大佬修成记-全系列视频地址:http://myhope365.com/news/index?id=66