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

    package test;
    
    public class Maopao {
    
        public static void main(String[] args) {
            int array[]=new int[]{0,8,-6,5,7,8,5};
            int[] smalltobig = smalltobig(array);
            for (int i : smalltobig) {
                System.out.println(i);
            }
            int[] bigtosmall = bigtosmall(array);
            System.out.println("-------------------------------");
            for (int i : bigtosmall) {
                System.out.println(i);
            }
        }
        public static int[] smalltobig(int[] a) {
            for (int i = 0; i < a.length-1; i++) {
                for (int j = i+1; j < a.length; j++) {//a[i]每次都是循环拿到最小值,所以内嵌for循环的起始值为a[i+1]
                    if(a[i]>a[j]){
                        int temp=a[i];
                        a[i]=a[j];
                        a[j]=temp;
                    }
                }
            }
            return a;
        }
        public static int[] bigtosmall(int[] b) {
            for (int i = 0; i < b.length-1; i++) {
                for (int j = i+1; j < b.length; j++) {//a[i]每次都是循环拿到最大值,所以内嵌for循环的起始值为a[i+1]
                    if(b[i]<b[j]){
                        int temp=b[i];
                        b[i]=b[j];
                        b[j]=temp;
                    }
                }
            }
            return b;
        }
    }

    从大到小:从第一个元素开始,依次和后面的每一个元素相比较,每次找出剩余元素中最大的;

    从大到小:从第一个元素开始,依次和后面的每一个元素相比较,每次找出剩余元素中最小的;

  • 相关阅读:
    LeetCode题解(2)-- Add Two Numbers
    LeetCode题解(1)--Two Sum
    STL review:vector & string & map & struct
    机器学习导论(一) 基本概念
    Single Number
    Single Number II
    Copy List with Random Pointer
    Word Break
    Populating Next Right Pointers in Each Node II
    Binary Tree Inorder Traversal
  • 原文地址:https://www.cnblogs.com/liqforstudy/p/5458420.html
Copyright © 2011-2022 走看看