Skip to content

Commit 0aa1109

Browse files
author
chenweijie
committed
优化插入排序算法
1 parent 8134967 commit 0aa1109

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

src/main/java/com/chen/algorithm/sort/InsertSort.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,11 @@ public class InsertSort {
99

1010
public static int[] sort(int[] array) {
1111

12-
int leftIndex;
1312
//从下标为1的元素开始选择合适的位置插入,因为下标为0的只有一个元素,默认是有序的
1413
for (int i = 1; i < array.length; i++) {
1514
//记录要插入的数据
1615
int temp = array[i];
17-
leftIndex = i - 1;
16+
int leftIndex = i - 1;
1817
//从已经排序的序列最右边的开始比较,找到比其小的数
1918
while (leftIndex >= 0 && temp < array[leftIndex]) {
2019
//向后挪动
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.chen.algorithm.study.test14;
2+
3+
import org.junit.Test;
4+
5+
/**
6+
* @author : chen weijie
7+
* @Date: 2020-05-11 00:34
8+
*/
9+
public class Solution3 {
10+
11+
public String longestCommonPrefix(String[] strs) {
12+
if (strs == null || strs.length == 0) {
13+
return "";
14+
}
15+
16+
String prex = strs[0];
17+
for (int i = 1; i < strs.length; i++) {
18+
19+
while (!strs[i].startsWith(prex)) {
20+
prex = prex.substring(0, prex.length() - 1);
21+
if (prex.isEmpty()) {
22+
return "";
23+
}
24+
}
25+
}
26+
return prex;
27+
}
28+
29+
@Test
30+
public void testCase() {
31+
String[] strings = {"flower", "flow", "flight"};
32+
33+
System.out.println(longestCommonPrefix(strings));
34+
35+
36+
}
37+
38+
}

0 commit comments

Comments
 (0)