1、用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
public class Solution {
     Stack<Integer> stack1 = new Stack<Integer>();
     Stack<Integer> stack2 = new Stack<Integer>();
      
     public void push(int node) {
         stack1.push(node);
     }
      
     public int pop() {
         while(!stack1.isEmpty()){
             stack2.push(stack1.pop());
         }
         int first=stack2.pop();
         while(!stack2.isEmpty()){
             stack1.push(stack2.pop());
         }
         return first;
     }
 }
2、冒泡排序
实现思路:
 (1)比较前后相邻的二个数据,如果前面数据大于后面的数据,就将这二个数据交换。
 (2)这样对数组的第0个数据到N-1个数据进行一次遍历后,最大的一个数据就“沉”到数组第 N-1个位置。
 (3)N=N-1,如果N不为 0就重复前面二步,否则排序完成。
  public static void bubbleSort1(){ 
     int i, j; 
     for(i=0; i<n; i++){//表示 n次排序过程。 
         for(j=1; j<n-i; j++){ 
             if(a[j-1] > a[j]){//前面的数字大于后面的数字就交换 
                 //交换a[j-1]和a[j] 
                 int temp; 
                 temp = a[j-1]; 
                 a[j-1] = a[j]; 
                 a[j]=temp; 
             } 
         } 
     } 
 }
3、算法思想:选择排序,从头至尾扫描序列,找出最小的一个元素,和第一个元素交换,接着从剩下的元素中继续这种选择和交换方式,最终得到一个有序序列。
public class SelectSort {
     public static void main(String[] args) {
         int [] arr = {49,38,65,97,76,13,27,49};
         selectSort(arr,arr.length);
     }
  
     public static void selectSort(int [] arr,int n){
         for (int i = 0; i < n - 1; i++) {
             int index = i;
             int j;
             // 找出最小值得元素下标
             for (j = i + 1; j < n; j++) {
                 if (arr[j] < arr[index]) {
                     index = j;
                 }
             }
             int tmp = arr[index];
             arr[index] = arr[i];
             arr[i] = tmp;
             System.out.println(Arrays.toString(arr));
         }
     }
 }

京公网安备 11010502036488号