1. 程式人生 > >資料結構(二)

資料結構(二)

***********************特殊的線性表-------棧****************************

棧: 先進後出、後進先出


棧的插入運算 叫做入棧

棧的刪除運算 叫做出棧

演示程式碼:

package com.chapter11;

//棧的介面
public interface IStack {

public void push(Object obj) throws Exception;

public Object pop() throws Exception;

public boolean isEmpty();
}

棧的實現類

package com.chapter11;

//使用順序儲存方式棧
public class StackImpl implements IStack{

private Object[] arr = new Object[5];

private int top = -1;
@Override
public void push(Object obj) throws Exception {

if(top>=arr.length-1){ //棧滿
throw new Exception("棧滿了");
}else{
top++;
arr[top] = obj;
System.out.println(obj + "入棧了");
}
}

@Override
public Object pop() throws Exception {
Object obj = null;

if(isEmpty()){//棧空
throw new Exception("棧空了");
}else{


obj = arr[top];

System.out.println(obj + "出棧了");

arr[top] = null;

top--;
}

return obj;
}

@Override
public boolean isEmpty() {
return top==-1;
}


public static void main(String[] args) throws Exception{
IStack stack = new StackImpl();

stack.push("aaa");
stack.push("bbb");
stack.push("ccc");
stack.push("ddd");
stack.push("eee");

stack.push("eee");

/*stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();

stack.pop();*/
}
}

 

***************************選擇排序*****************************

int[] intArr = {26,7,16,23,33,8};


第一輪: 選擇出最小的 和第一個數進行交換

比較結果
{7, 26,16,23,33,8}


第二輪比較結果


{7,8, 16,23,33,26}


第三輪比較結果


{7,8,16, 23,33,26}


第四輪比較結果


{7,8,16,23, 33,26}


第五輪比較結果

{7,8,16,23,26, 33}

 

演示程式碼:

package com.chapter11;

/**
* 公司:藍橋軟體學院 作者:zhangzy 時間:2017年7月14日 下午2:17:08 功能:演示選擇排序
*/
public class TestChoiceSorted {

public static void main(String[] args) {

int[] intArr = { 26, 7, 16, 23, 33, 8};

int temp;
// 總共比較多少輪 = 元素個數 - 1

// 一共比較了多少次 = n*(n-1)/2
//時間複雜度 O(n方)
//空間複雜度O(1)
//每一輪比較了多少次 = 元素的個數 - 輪數 次
//第一輪 比較了5次
//第二輪 比較了4次
//第三輪 3次
//第四輪 2次
//第五輪 1次
for (int j = 0; j < intArr.length - 1; j++) {

// 先寫一輪
// 第一輪: 選擇出最小的 和第一個交換
// 如何找最小
// 打擂臺: 假設第一個數是最小的 然後和後面的數進行比較

int min = j;// 假設第一個數是最小的
for (int i = min + 1; i < intArr.length; i++) {

if (intArr[min] > intArr[i]) {
min = i;
}
}

if (min != j) {

// temp intArr[min] intArr[0]
temp = intArr[min];
intArr[min] = intArr[j];
intArr[j] = temp;
}
}

System.out.println("選擇排序後");

for (int i : intArr) {
System.out.print(i + " ");
}

}
}