我是靠谱客的博主 缥缈唇彩,这篇文章主要介绍字符串数组的排序,现在分享给大家,希望可以做个参考。

Java毕向东课程小练习:字符串数组的排序
第一步,定义好数组后,写一个排序数组的方法。
思路:

  1. 曾经玩过int数组排序:选择,冒泡。
  2. 字符串排序同理。
  3. for嵌套循环4. 循环中进行元素大小的比较,满足条件就进行位置置换数值比较可以使用比较运算符,但是对象比较必须使用方法。比较对象的方法:compare 字符串排序同理。
  4. 循环中进行元素大小的比较,满足条件就进行位置置换数值比较可以使用比较运算符。

但是对象比较必须使用方法。比较对象的方法:compare
compareTo方法用于两个同类型的数据比较,不能用来比较不同类型,如果指定的值等于参数:返回值0,如果指定的值小于参数 :返回值-1,如果指定的值大于参数:返回值1
因为java里的 if 括号里必须是Boolean值,不能是0,1,-1。所以我们需要写成比较形式,如果第一个数大于第二个数,那么返回1,1>0,那么进行调换位置。0和-1(小于等于)都不用进行调换位置。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Arrays; public class Demo{ public static void main(String[] args){ String[] strs = {"abc","nba","cctv","itcast"}; printArray(strs); sortString(strs); printArray(strs); sortMethod(strs); printArray(strs); } /** * 打印数组 */ private static void printArray(String[] strs) { for (int i = 0; i < strs.length; i++) { System.out.print(strs[i]+","); } System.out.println(); } /** * 字符串数组排序 */ public static void sortString(String[] strs) { for (int i = 0; i < strs.length-1; i++) { for (int j = i+1; j < strs.length-1; j++) { if(strs[i].compareTo(strs[j])>0){ swap(strs,i,j); } } } } /** * 数组元素位置替换 */ private static void swap(String[] strs, int i, int j) { String temp = strs[i]; strs[i] = strs[j]; strs[j] = temp; } /** * java自己的排序方法,直接调用 */ public static void sortMethod(String[] strs){ Arrays.sort(strs); } }```

最后

以上就是缥缈唇彩最近收集整理的关于字符串数组的排序的全部内容,更多相关字符串数组内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(108)

评论列表共有 0 条评论

立即
投稿
返回
顶部