美文网首页
面试中的几种排序方法(冒泡、插入、选择)

面试中的几种排序方法(冒泡、插入、选择)

作者: c3e1ce81199b | 来源:发表于2018-11-25 00:04 被阅读0次
  1. 冒泡排序
//相邻的两个比较->交换->完成排序
    public static void Sort(int[] nums) {
        int temp;
        int size = nums.length;
        for (int i = 0; i < size - 1; i++) {
            for (int j = 0; j < size - 1 - i; j++) {
                if (nums[j] > nums[j + 1]) {  //递增交换
                    temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(nums));
    }

    @Test
    public void testDemo() {
        int[] nums = {1,5,6,3,8,0,4,2,5,68,};
        BubbleSort.Sort(nums);
    }
  1. 插入排序

    public static void Sort(int[] nums) {
        int size = nums.length;
        int temp, j; //临时数据
        for (int i = 0; i < size; i++) {
            temp = nums[i];
            for (j = i; j > 0 && temp < nums[j - 1]; j--) {
                nums[j] = nums[j - 1];
            }
            nums[j] = temp;
        }
        System.out.println(Arrays.toString(nums));
    }

    @Test
    public void testDemo() {
        int[] nums = {1, 5, 6, 3, 8, 0, 4, 2, 5, 68,};
        InsertSort.Sort(nums);
    }
  1. 选择排序

        public static void selectSort(int[] nums) {

            /**
             * 在要排序的一组数中,选出最小的一个数与第一个位置的数交换;
                然后在剩下的数当中再找最小的与第二个位置的数交换,
                如此循环到倒数第二个数和最后一个数比较为止。
             */
            int size = nums.length; //数组的长度
            int index = 0, temp = 0; //记录元素位置,temp 为交换的中间变量

            for (int i = 0; i < size; i++) {
                index = i;
                for (int j = size - 1; j > i; j--) {
                    if (nums[index] > nums[j]) {
                        temp = nums[index];
                        nums[index] = nums[j];
                        nums[j] = temp;
                    }
                }
            }
            System.out.println(Arrays.toString(nums));
        }

    @Test
    public void testDemo() {
        int[] nums = {1, 5, 6, 3, 8, 0, 4, 2, 5, 68,};
        BubbleSort.Sort(nums);
    }
  1. 菱形输出

    @Test
    public void name2() {
        int size=6;
        for (int x = -size; x <= size; x++) {
            for (int y = -size; y <= size; y++) {
                if (Math.abs(x) + Math.abs(y) <= size) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println("");
        }
    }

输出结果:
      *      
     ***     
    *****    
   *******   
  *********  
 *********** 
*************
 *********** 
  *********  
   *******   
    *****    
     ***     
      *      

相关文章

网友评论

      本文标题:面试中的几种排序方法(冒泡、插入、选择)

      本文链接:https://www.haomeiwen.com/subject/amyuqqtx.html