zoukankan      html  css  js  c++  java
  • Java全排列排序

    全排列算法,递归的实现

    
    public class AllSort {
    	public static void main(String[] args) {
    		String str[] = { "1", "2", "3" };
    		permutation(str, 0, str.length);
    	}
    
    	static void swap(String[] str, int start, int end) {
    		String tmep = str[start];
    		str[start] = str[end];
    		str[end] = tmep;
    	}
    
    	static void permutation(String[] str, int start, int end) {
     //判断是否遍历完
    		if (start == end - 1) {
    			 for (int i = 0; i < end; i++) {
    			 System.out.print(str[i]);
    			 }
    			System.out.println();
    		} else {
    			for (int i = start; i < end; i++) {
    				swap(str, start, i);
    				permutation(str, start + 1, end);//后续遍历
                                    //还原遍历的结果  
    				swap(str, start, i);
    			}
    
    		}
    	}
    }
    

    Java排序

    		int[] array = new int[] { 34, 68, 1, 832, 5, 87 };
    		// 冒泡排序
    		for (int i = 0; i < array.length - 1; i++) {
    			for (int j = i + 1; j < array.length; j++) {
    				if (array[i] > array[j]) {
    					int temp = array[i];
    					array[i] = array[j];
    					array[j] = temp;
    
    				}
    			}
    		}
    
    		// 插入排序 每步将一个待排序的记录,按其顺序码大小插入到前面已经排序的字序列的合适位置,直到全部插入排序完为止。
    		// 关键问题:在前面已经排好序的序列中找到合适的插入位置。
    		int j, temp;
    		for (int i = 1; i < array.length; i++) {
    			temp = array[i];
    			for (j = i; j > 0 && temp < array[j - 1]; j--) {
    				array[j] = array[j - 1];
    			}
    			array[j] = temp;
    		}
    
    		// 选择排序 首先通过n-1次关键字比较,从n个记录中找出关键字最小的记录,将它与第一个记录交换;
    		// 再通过n-2次比较,从剩余的n-1个记录中找出关键字次小的记录,将它与第二个记录交换;
    		// 重复上述操作,共进行n-1趟排序后,排序结束。
    
    		int postion, temp;
    		for (int i = 0; i < array.length; i++) {
    			postion = i;
    			for (int j = array.length - 1; j > i; j--) {
    				if (array[j] < array[postion]) {
    					postion = j;
    				}
    			}
    			temp = array[i];
    			array[i] = array[postion];
    			array[postion] = temp;
    		}
    
    
    
  • 相关阅读:
    IDEA service/DashBoard 不显示服务端口号
    是否同一棵二叉搜索树
    Tree Traversals Again
    有符号数移位
    tl431基准的用法
    7寸屏电压方案
    test
    合并commit
    重命名commit
    Git 在公司内部的使用规范
  • 原文地址:https://www.cnblogs.com/tonyY/p/4923466.html
Copyright © 2011-2022 走看看