数据结构(二)

***********************特殊的线性表-------栈****************************

栈: 先进后出、后进先出


栈的插入运算 叫做入栈

栈的删除运算 叫做出栈

演示代码:

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 + " ");
}

}
}

猜你喜欢

转载自www.cnblogs.com/MrTanJunCai/p/9906805.html