zoukankan      html  css  js  c++  java
  • Java和Python分别实现直接选择排序

    1.基本思想

      将指定排序位置与其他数组元素分别对比,如果满足条件就进行交换。个人理解其实就是每趟循环从数组里选一个最大的值(最小的值)放到数组最后(最前)。

    2.算法实现

      这里以每趟循环从数组中选择一个最大的值来实现。可知,只需进行 n-1次循环,便能完成排序。

      Java实现代码如下:

     1 public class SelectSort {
     2     public static void main(String[] args) {
     3         int arr[] = {64,4,24,1,3,15};
     4         SelectSort sorter = new SelectSort();
     5         sorter.sorted(arr);
     6     }
     7     
     8     
     9     public void sorted(int arr[]) {
    10         for(int i = 0;i < arr.length - 1;i++) {//循环n-1次,每次循环确定一个值的位置
    11             int index = 0;
    12             for(int j = 0;j < arr.length - i;j++) {//比较元素的个数每次会减少一个
    13                 if(arr[index] < arr[j]) {//每次循环选择出一个最大的值,并用index标记位置 
    14                     index = j;
    15                 }
    16             }
    17                         //实现指定位置与index标记位置的元素交换
    18             int temp = arr[arr.length-i-1];
    19             arr[arr.length-i-1] = arr[index];
    20             arr[index] = temp;
    21         }
    22         showArray(arr);
    23     }
    24     
    25     
    26     public void showArray(int arr[]) {
    27         for(int i = 0;i < arr.length;i++) { 
    28             if(i < arr.length - 1) {
    29                 System.out.print(arr[i]+"、");
    30             }else {
    31                 System.out.print(arr[i]);
    32             }
    33         }
    34     }
    35 }

    Python代码实现如下:

    # -*- coding: utf-8 -*-
    
    def SelectSort(list1):
        for i in range(len(list1)-1)://循环n-1次
            index = 0
            for j in range(len(list1)-i)://比较元素个数随循环次数递减
                if lsit1[index] < list1[j]:
                    index = j
            temp = list1[len(list1)-1-i]
            list1[len(list1)-1-i] = list1[index]
            list1[index] = temp
            print("第{}次排序结果为:
    ".format(str(i+1)) + str(list1))
        return list1
    
    if __name__ == '__main__':
        lista = [63,4,24,3,1,15]
        list2 = SelectSort(lista)
        print("最终结果为:
    "+str(list2))
  • 相关阅读:
    MYSQL函数 Cast和convert的用法详解
    MySQL5.7.9(GA)的安装
    TMS Scripter importtool的使用
    MySQL 高可用架构在业务层面的应用分析
    UNIGUI:How to redirect and close session?
    HTML URL 编码:请参阅:http://www.w3school.com.cn/tags/html_ref_urlencode.html
    js 解决函数加载的问题
    必备函数
    Action 分离
    JavaScript.Remove
  • 原文地址:https://www.cnblogs.com/xiang9286/p/9638548.html
Copyright © 2011-2022 走看看