(1)算法基本功——快速排序
代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*快速排序
*/
public class QuickSort {
private static int partition(Object[] data, int first, int end) {
while (first < end) {
while (first < end && (Integer)data[first] <= (Integer)data[end]) { //右扫描
end--;
}
if (first < end) {
int temp = (Integer)data[first];
data[first] = data[end];
data[end] = temp;
first++;
}
while (first < end && (Integer)data[first] <= (Integer)data[end]) { //左扫描
first++;
}
if (first < end) {
int temp = (Integer)data[first];
data[first] = data[end];
data[end] = temp;
end--;
}
}
return first;
}
private static void sort(Object[] data, int first, int end) {
if (first < end) {
int pivot = partition (data, first, end);
sort(data, first, pivot-1);
sort(data, pivot+1, end);
}
}
private static Object[] getData() {
BufferedReader reader;
List<Integer> data = null;
try {
File file = new File("src/dataFile/largeW.txt");
reader = new BufferedReader(new FileReader(file));
data = new ArrayList<Integer>();
String temp = reader.readLine();
while (temp != null) {
data.add(Integer.valueOf(temp.trim()));
temp = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data.toArray();
}
private static void write2File(Object[] data) {
FileWriter output = null;
try {
output = new FileWriter(new File("src/dataFile/largeW_merge.txt"));
for (int i=0; i<data.length; i++) {
Integer integer = (Integer)data[i];
output.write(integer + "\n");
}
output.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Object[] testData = getData();
sort(testData, 0, testData.length-1);
write2File(testData);
}
}
运行结果:
(2)经典算法面试题
- 写一个函数,检查字符是否是整数,如果是,返回其整数值。(或者:怎样只用4行代码编写出一个从字符串到长整形的函数?)
public class Test{
public static void main(String[] args) {
System.out.println(getLong("asdf456sa4df654"));
System.out.println(getLong("1984797613215"));
}
private static Long getLong(String str) {
try {
return Long.valueOf(str);
} catch (Exception e) {
return -1L;
}
}
}
在此处默认如果输入的不是整数的话,则返回-1。
输出结果: