zoukankan      html  css  js  c++  java
  • 冒泡排序与选择排序

    一、冒泡排序

     1 package day0911;
     2 
     3 import java.util.Arrays;
     4 
     5 /**
     6  * 冒泡排序
     7  */
     8 public class MaoPaoPaiXu {
     9     public static void main(String args[]){
    10         //定义一个数组
    11         int [] maopao = {32,16,68,54,97,85,13,20};
    12         //外层循环-1,maopao.length表示数组长度
    13         for(int i=0;i<maopao.length-1;i++){
    14             //内层循环-1-i,总共八个数
    15             for (int j=0;j<maopao.length-1-i;j++){
    16                 //定义一个空瓶子
    17                 int temp = 0;
    18                 //三个空瓶子互换模式
    19                 //如果前面的大于后面的,则把前面的数换到后面来,从小到大排序
    20                 //如果想从大到小排序,则用小于符号
    21                 if (maopao[j]>maopao[j+1]){
    22                     //如果maopao[j]大于后面的,则赋值给空瓶子
    23                     //如果不大于,则maopao[j]位置不变
    24                     temp=maopao[j];
    25                     //如果前后对比数值小,则前移
    26                     maopao[j]=maopao[j+1];
    27                     //前后数值对比较大的数往后移
    28                     maopao[j+1]=temp;
    29                 }
    30             }
    31             //内层循环每次都要执行打印
    32             //System.out.print(Arrays.toString(maopao));
    33         }
    34         //想要输出数组类型就得用Arrays.toString
    35         System.out.print(Arrays.toString(maopao));
    36     }
    37     
    38 }

    二、选择排序

    package day1010;
    
    /**
     * @author donleo
     * date 2019-10-10
     * code 选择排序
     */
    
    public class SelectionSort {
        public static void main(String[] args) {
            //模拟数据
            int[] array = {52, 63, 14, 59, 68, 35, 8, 67, 45, 99};
            System.out.println("原数组:");
            for (int i : array){
                System.out.print(i+" ");
            }
            System.out.println();
            SelectionSort(array);
            System.out.println("排序后:");
            for (int i : array){
                System.out.print(i+" ");
            }
    
        }
    
        public static void SelectionSort(int arr[]){
            for (int i=0;i<arr.length-1;i++){
                int min = i;
                for (int j=i+1;j<arr.length-1;j++){
                    if (arr[j]<arr[min]){
                        min=j;
                    }
                }
                if (min!=i){
                    swap(arr,i,min);
                }
            }
        }
    
        public static void swap(int arr[],int a,int b){
            int temp=arr[a];
            arr[a] = arr[b];
            arr[b] = temp;
        }
    }
  • 相关阅读:
    AOP概述
    函数调用规定
    lexical scoping vs. dynamic scoping
    [C++]C++11新特性
    JavaScript Tutorial 05 #Class#
    JavaScript Tutorial 04 #Function#
    JavaScript Tutorial 03 #Array#
    JavaScript Tutorial 02 #Object#
    JavaScript Tutorial 01 #Basic#
    Win32 Thread Information Block
  • 原文地址:https://www.cnblogs.com/donleo123/p/11649757.html
Copyright © 2011-2022 走看看