a- package demo.collection;
- import java.util.Arrays;
- public class SortStringDemo {
- /**
- * 1、给定一个字符串数组,按照字典顺序进行从小到大的排序。
- * {"nba","abc","cba","zz","qq","haha"}
- */
- public static void main(String[] args) {
- String[] str = new String[]{"nba","abc","cba","zz","qq","haha"};
- printString(str);
- // Arrays.sort(str);
- // bubbleSort(str);
- selectSort(str);
- printString(str);
- }
- //选择排序
- private static void selectSort(String[] str) {
- for (int i = 0; i < str.length - 1; i++) {
- for (int j = 1+i; j < str.length; j++) {
- if (str[i].compareTo(str[j]) > 0) {
- String temp = str[j];
- str[j] = str[i];
- str[i] = temp;
- }
- }
- }
- }
- //冒泡排序
- private static void bubbleSort(String[] str) {
- for (int i = 0; i < str.length - 1; i++) {
- for (int j = 0; j < str.length - 1 - i; j++) {
- if (str[j].compareTo(str[j + 1]) > 0) {
- String temp = str[j];
- str[j] = str[j + 1];
- str[j + 1] = temp;
- }
- }
- }
- }
- private static void printString(String[] str) {
- String temp = "";
- for(String s:str)
- temp += s+" ";
- System.out.println(temp);
- }
- }
复制代码
|
|