package Recursion;
public class EightQueen {
static int max = 8;
static int[] arr = new int[max];
static int count=0;
public static void main(String[] args) {
check(0);
}
private static void print(){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
count++;
System.out.println(count);
}
private static boolean judge(int n){
for (int i = 0; i < n; i++) {
if (arr[i]==arr[n]||Math.abs(n-i)==Math.abs(arr[n]-arr[i])){
return false;
}
}
return true;
}
private static void check(int n){
if (n==max){
print();
return;
}
else {
for (int i = 0; i < max; i++) {
arr[n]=i;
if (judge(n)){
check(n+1);
}
}
}
}
}
package Sort;
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] arr ={3,9,-1,10,2};
int temp = 0;
for (int i = 0; i < arr.length-1; i++) {
for (int j = 0; j < (arr.length-1-i); j++) {
if (arr[j+1]<arr[j]){
temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
代码实现(可提前结束)
package Sort;
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] arr ={3,9,-1,10,2};
boolean flag = false;
int temp = 0;
for (int i = 0; i < arr.length-1; i++) {
flag = false;
for (int j = 0; j < (arr.length-1-i); j++) {
if (arr[j+1]<arr[j]){
flag=true;
temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
if (!flag){
break;
}
}
System.out.println(Arrays.toString(arr));
}
}
|