1. 快速/冒泡排序
public class OrderTest {
public static void main(String[] args) {
int[] array = {2,1,343,2,43,431,7,49};
// 冒泡排序
//bubbleSort(array);
//快速排序
quickSort(array,0,7);
}
public static void bubbleSort(int[] array) {
int temp;
for(int i=0; i< array.length; i++) {
for(int j=0;j<array.length-1-i;j++) {
if (array[j]>array[j+1]) {
temp = array[j];
array[j]=array[j+1];
array[j+1]= temp;
}
}
}
System.out.println(Arrays.toString(array));
}
public static void quickSort(int[] array,int low,int high) {
int i,j,temp,t;
if (low > high) {
return;
}
i = low;
j = high;
temp = array[i];
while(i < j) {
while(array[j] >= temp && j > i) {
j--;
}
while(array[i] <= temp && j > i) {
i++;
}
if (j>i) {
t = array[j];
array[j] = array[i];
array[i] = t;
}
}
array[low] = array[i];
array[i] = temp;
System.out.println(temp + Arrays.toString(array));
quickSort(array, low, j-1);
quickSort(array, i+1, high);
}
}
2. 杨辉三角
public class Triangle {
private static Scanner sc;
private static int n;
private static int[][] triangleArray;
public static void main(String[] args) {
sc = new Scanner(System.in);
n = sc.nextInt();
triangleArray = new int[n][n];
for(int i=0; i<n; i++) {
triangleArray[i][0] = triangleArray[i][i] = 1;
for(int j=1;j<i;j++) {
triangleArray[i][j] =triangleArray[i-1][j-1] +triangleArray[i-1][j];
}
}
display();
}
private static void display() {
int i, j;
for(i = 0; i < n; i++) {
// 前面空格个数
for(j = n - i - 1; j > 0; j--) {
System.out.print(" ");
}
// 每个数占3格,且每个数之间空1格
for(j = 0; j < i; j++) {
System.out.printf("%3d ", triangleArray[i][j]);
}
// 最后1个数,换行
System.out.printf("%3d\n", triangleArray[i][j]);
}
}
}
3.先进先出队列
public class Queue {
private int maxSize;
private Object[] queueArray;
private int front;
private int rear;
private int size;
public Queue(int length) {
maxSize = length;
queueArray = new Object[maxSize];
front = 0;
rear = -1;
size = 0;
}
public boolean isFull(){
return (rear + 2 == front || front + maxSize -2 == rear);
}
public boolean isEmpty(){
return (rear + 1 == front || front + maxSize -1 == rear);
}
public String enQueue(String str) {
if (isFull()) {
throw new RuntimeException("队列已满," + str + " 不能入队!");
}
queueArray[++rear] = str;
size++;
return str;
}
public String deQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空," + " 不能出队!");
}
String str = (String) queueArray[front++];
size--;
return str;
}
public int queueSize() {
return size;
}
public static void main(String[] args) {
Queue queue = new Queue(5);
queue.enQueue("a");
queue.enQueue("b");
queue.enQueue("c");
queue.enQueue("d");
//queue.enQueue("e");
System.out.println("队列是否为空: " + queue.isEmpty() + " 队列是否满: " + queue.isFull());
System.out.println("队列大小:" + queue.queueSize());
int size = queue.queueSize();
for(int i = 0; i < size; i++){
String str = queue.deQueue();
System.out.print(str + " ");
}
}
}