This commit is contained in:
wangzheng 2018-10-16 17:57:57 +08:00
commit 53a608e769
28 changed files with 1839 additions and 43 deletions

View File

@ -0,0 +1,122 @@
/**
* 1
* 2
* 31.5 10
*
* Authorcaozx
* time 20181011
*/
#include <iostream>
#include "StackBasedOnArray.h"
using namespace std;
//构造函数,创建栈
//类模板成员函数的写法 template<class T> 返回值类型 类名<T>::成员函数名(参数列表){}
template<class T> ArrayStack<T>::ArrayStack()
{
this -> count = 10;
this -> flag = 0;
this -> array = new T[this -> count];
if (! this -> array){
cout << "array malloc memory failure" << endl;
}
}
//有参构造函数,创建栈
template<class T> ArrayStack<T>::ArrayStack(int count)
{
this -> count = count;
this -> flag = 0;
this -> array = new T[this -> count];
if (! this -> array){
cout << "array malloc memory failure" << endl;
}
}
//析构函数,销毁栈
template <class T> ArrayStack<T>::~ArrayStack(){
this -> count = 0;
this -> flag = 0;
if(this -> array){
delete [] this -> array;
this -> array = NULL;
}
}
// 入栈
template<class T> void ArrayStack<T>::push(T data){
if(this -> flag == this -> count){
cout << "The stack is full , so need to enlarge 1.5x! "<< endl;
this -> count = int (1.5 * this -> count);
T * temp = new T [this -> count];
for(int i = 0; i < this -> flag ; i++){
temp[i] = this -> array[i];
//cout << temp[i] <<endl;
}
delete [] this -> array; //释放原来的空间
temp[this -> flag] = data;
this -> flag ++;
this -> array = temp;
}
else{
this -> array [this -> flag] = data;
this -> flag ++ ;
}
}
//出栈,并删除栈顶元素
template<class T> T ArrayStack<T>::pop(){
this -> flag --;
T temp = this -> array[this -> flag];
return temp;
}
//出栈,不删除栈顶元素
template<class T> T ArrayStack<T>::peek(){
T temp = this -> array[this -> flag - 1];
return temp;
}
template<class T> int ArrayStack<T>::stackSize(){
return this -> flag;
}
template<class T> int ArrayStack<T>::stackMaxSize(){
return this -> count;
}
int main(int argc, char const *argv[])
{
cout << " === test begin ===" << endl;
ArrayStack <int> arrstack(12);
arrstack.push(10);
arrstack.push(20);
arrstack.push(30);
arrstack.push(40);
arrstack.push(50);
arrstack.push(60);
arrstack.push(70);
arrstack.push(80);
arrstack.push(90);
arrstack.push(100);
arrstack.push(110);
arrstack.push(120);
arrstack.push(130);
arrstack.push(140);
arrstack.push(150);
cout << "peek , not delete " << arrstack.peek() << endl;
cout << "pop , delete " << arrstack.pop()<<endl;
arrstack.push(210);
arrstack.push(220);
cout << "peek , not delete " << arrstack.peek() << endl;
cout << "pop , delete " << arrstack.pop()<<endl;
system("pause");
return 0;
}

View File

@ -0,0 +1,20 @@
// 类模板的声明(line 3),类模板实例化后就是模板类
// 类模板声明的写法 template <class T> class 类名{}
template <class T> class ArrayStack
{
public:
ArrayStack();
ArrayStack(int count);
~ArrayStack();
void push(T data); //入栈
T pop(); //出栈,并删除栈顶元素
T peek(); //返回栈顶元素,不删除栈顶元素,栈顶指针不变
int stackSize();
int stackMaxSize();
private:
int flag; //栈顶标签,指向栈顶
int count ; //栈的容量
T *array; //指针
};

View File

@ -0,0 +1,127 @@
/**
* 1
* 2
* 3
* 4pop和peek nullcpp默认返回的是0
* *
* * 使size函数判断以下
* Authorcaozx
* time 20181011
*/
#include <iostream>
#include "StackBasedOnLinkedList.h"
using namespace std;
template<class T> LinkedListStack<T>::LinkedListStack()
{
this -> count = 0;
this -> head = new LinkedNode;
this -> head -> next = NULL;
}
template<class T> LinkedListStack<T>::~LinkedListStack()
{
LinkedNode * ptr, * temp;
ptr = head;
while(ptr -> next != NULL){
temp = ptr -> next;
ptr -> next = temp -> next;
delete temp;
}
delete head ; //删除头节点
this -> head = NULL;
this -> count = 0;
}
// 入栈
template<class T> void LinkedListStack<T>::push(const T & data)
{
LinkedNode * insertPtr = new LinkedNode;
insertPtr -> data = data;
insertPtr -> next = this -> head -> next;
head -> next = insertPtr;
this -> count ++;
cout << "push data : " << this -> head -> next -> data << endl;
}
//返回栈顶元素,即出栈,不删除栈顶元素
template<class T> T LinkedListStack<T>::peek()
{
if(this -> count == 0 || this -> head -> next == NULL){
cout << " stack is empty, peek fail"<< endl;
return NULL;
}
else{
return this -> head -> next -> data;
}
}
//出栈,删除栈顶元素
template<class T> T LinkedListStack<T>::pop()
{
if(this -> count == 0 || this -> head -> next == NULL){
cout << " stack is empty, pop fail"<< endl;
return NULL;
}
else{
LinkedNode * temp = this -> head -> next;
this -> head -> next = temp -> next;
T data = temp -> data;
delete temp;
this -> count --;
return data;
}
}
//返回栈的大小
template<class T> int LinkedListStack<T>::size() const
{
return this -> count;
}
int main(int argc, char const *argv[])
{
cout << " === StackBasedOnLinkedList test begin ===" << endl;
LinkedListStack <float> stack;
cout << "size==="<<stack.size()<<endl;
stack.push(10.1);
stack.push(20.2);
stack.push(30.);
stack.push(40.4);
stack.push(50.5);
stack.push(60.6);
cout << "size==="<<stack.size()<<endl;
cout << "stack peek " << stack.peek() << endl;
cout << "stack pop " << stack.pop() << endl;
cout << "size==="<<stack.size()<<endl;
cout << "stack pop " << stack.pop() << endl;
cout << "stack pop " << stack.pop() << endl;
cout << "stack pop " << stack.pop() << endl;
cout << "stack pop " << stack.pop() << endl;
cout << "stack pop " << stack.pop() << endl;
cout << "size==="<<stack.size()<<endl;
cout << "stack pop " << stack.pop() << endl;
cout << "stack peek " << stack.peek() << endl;
stack.push(110.1);
stack.push(120.2);
stack.push(130.3);
stack.push(140.4);
stack.push(150.5);
stack.push(160.6);
cout << "size==="<<stack.size()<<endl;
cout << "stack peek " << stack.peek() << endl;
cout << "stack pop " << stack.pop() << endl;
cout << "stack pop " << stack.pop() << endl;
cout << "stack pop " << stack.pop() << endl;
cout << "stack peek " << stack.peek() << endl; //peek
cout << "stack pop " << stack.pop() << endl;
cout << "stack pop " << stack.pop() << endl;
cout << "stack pop " << stack.pop() << endl;
cout << "size==="<<stack.size()<<endl;
cout << "stack peek " << stack.peek() << endl; //peek
cout << "stack pop " << stack.pop() << endl;
system("pause");
return 0;
}

View File

@ -0,0 +1,20 @@
// 类模板的声明,关键字 class 也可以更换成 typename
template<class T> class LinkedListStack
{
public:
LinkedListStack();
~LinkedListStack();
void push(const T & data); //入栈
T peek(); //返回栈顶元素,即出栈,不删除栈顶元素
T pop(); //出栈,删除栈顶元素
int size() const; //返回栈的大小
private:
int count; //存放栈的大小,因为是单链表所以这里不规定栈的最大可承载量
struct LinkedNode
{
T data;
LinkedNode * next;
};
LinkedNode * head; // 单链表的头指针,不带头节点
};

View File

@ -0,0 +1,161 @@
/*************************************************************************
> File Name: arrayStack.c
> Author: jinshaohui
> Mail: jinshaohui789@163.com
> Time: 18-10-12
> Desc:
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"./arrayStack.h"
/*创建并初始化顺序栈*/
stArrayStack * arrayStack_create(int size)
{
stArrayStack *parrStack = NULL;
parrStack = (stArrayStack *)malloc(sizeof(stArrayStack));
if (parrStack == NULL)
{
return NULL;
}
parrStack->size = size;
parrStack->pos = -1;
parrStack->array = (int *)malloc(sizeof(int)*size);
if(parrStack->array == NULL)
{
free(parrStack);
return NULL;
}
return parrStack;
}
/*销毁顺序栈*/
void arrayStack_destory(stArrayStack * parrStack)
{
if(parrStack == NULL)
{
return;
}
if (parrStack->array != NULL)
{
free(parrStack->array);
}
free(parrStack);
return;
}
/*出栈*/
int arrayStack_pop(stArrayStack *parrStack)
{
int data = 0;
if(arrayStack_is_empty(parrStack))
{
return -1;
}
data = parrStack->array[parrStack->pos];
parrStack->pos--;
return data;
}
/*入栈*/
int arrayStack_push(stArrayStack *parrStack,int data)
{
if(arrayStack_is_full(parrStack))
{
return -1;
}
parrStack->pos++;
parrStack->array[parrStack->pos] = data;
return 0;
}
int arrayStack_push_new(stArrayStack*parrStack,int data)
{
int *ptmp = NULL;
/*如果栈不满,直接插入*/
if(!arrayStack_is_full(parrStack))
{
return arrayStack_push(parrStack,data);
}
/*如果栈已经满,申请内存*/
ptmp = (int *)malloc(2*parrStack->size*sizeof(int));
if (ptmp == NULL)
{
return -1;
}
memcpy(ptmp,parrStack->array,parrStack->size*sizeof(int));
free(parrStack->array);
parrStack->array = ptmp;
parrStack->size = 2*parrStack->size;
parrStack->pos++;
parrStack->array[parrStack->pos] = data;
return ;
}
void arrayStack_dump(stArrayStack *parrStack)
{
int i = 0;
if (arrayStack_is_empty(parrStack))
{
printf("\r\n arrayStack is empty.");
return;
}
printf("\r\narrayStack size = %d,pos= %d,",
parrStack->size,parrStack->pos);
for(i = 0; i <= parrStack->pos; i++)
{
printf("\r\narry[%d] = %d",i,parrStack->array[i]);
}
}
int main()
{
int i = 0;
int ret = 0;
stArrayStack * parrStack = NULL;
printf("\r\n create size = 4 arrayStack.");
parrStack = arrayStack_create(4);
if (parrStack == NULL)
{
printf("\r\n create size = 4 arrayStack faided.");
return 0;
}
for (i = 0; i < 5; i++)
{
ret = arrayStack_push(parrStack,i);
if(ret != 0)
{
printf("\r\n push size = %d arrayStack faided.",i);
}
}
arrayStack_dump(parrStack);
ret = arrayStack_push_new(parrStack,4);
if(ret != 0)
{
printf("\r\n push size = %d arrayStack faided.",4);
}
arrayStack_dump(parrStack);
arrayStack_destory(parrStack);
return;
}

View File

@ -0,0 +1,23 @@
/*************************************************************************
> File Name: arrayStack.h
> Author: jinshaohui
> Mail: jinshaohui789@163.com
> Time: 18-10-12
> Desc:
************************************************************************/
#ifndef ARRAY_STACJ_H
#define ARRAY_STACJ_H
typedef struct _array_stack
{
int size;/*栈的大小*/
int pos;/*当前存储元素的个数,即栈顶元素下表*/
int *array;/*数据存储区*/
}stArrayStack;
#define arrayStack_size(arrayStack) (arrayStack->size)
#define arrayStack_is_empty(arrayStack) (arrayStack->pos == -1)
#define arrayStack_is_full(arrayStack) (arrayStack->pos == (arrayStack->size-1))
#endif

View File

@ -0,0 +1,136 @@
/*************************************************************************
> File Name: linklist_stack.c
> Author: jinshaohui
> Mail: jinshaohui789@163.com
> Time: 18-10-12
> Desc:
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "./linklist_stack.h"
linklist_stack * stack_create()
{
linklist_stack * stack = NULL;
stack = (linklist_stack *)malloc(sizeof(linklist_stack));
if (stack == NULL)
{
return NULL;
}
stack->next = NULL;
return stack;
}
void stack_destory(linklist_stack* stack)
{
linklist_stack * ptmp = NULL;
while(!stack_is_empty(stack))
{
ptmp = stack->next;
stack->next = stack->next->next;
free(ptmp);
}
free(stack);
return;
}
int stack_push(linklist_stack *stack,int data)
{
linklist_stack * ptmp = NULL;
ptmp = (linklist_stack *)malloc(sizeof(linklist_stack));
if (ptmp == NULL)
{
return -1;
}
ptmp->data = data;
ptmp->next = stack->next;
stack->next = ptmp;
return 0;
}
int stack_pop(linklist_stack*stack,int *data)
{
linklist_stack *ptmp = NULL;
if (data == NULL)
{
return -1;
}
if(stack_is_empty(stack))
{
return -1;
}
*data = stack->next->data;
ptmp = stack->next;
stack->next = ptmp->next;
free(ptmp);
return 0;
}
void stack_dump(linklist_stack *stack)
{
linklist_stack * ptmp = stack->next;
while(ptmp != NULL)
{
printf("\r\n data = %d",ptmp->data);
ptmp = ptmp->next;
}
return;
}
int main()
{
int i = 0;
int ret = 0;
int data = 0;
linklist_stack * stack = NULL;
stack = stack_create();
if (stack == NULL)
{
printf("\r\n stack create falied.");
return 0;
}
for (i = 0; i < 4; i++)
{
ret = stack_push(stack,i);
if(ret != 0)
{
printf("\r\n stack push %d falied.",i);
}
}
stack_dump(stack);
for (i = 0; i < 5; i++)
{
ret = stack_pop(stack,&data);
if(ret != 0)
{
printf("\r\n stack pop%d falied.", i);
}
else
{
printf("\r\n data = %d,",data);
}
}
stack_destory(stack);
return 0;
}

View File

@ -0,0 +1,22 @@
/*************************************************************************
> File Name: linklist_stack.h
> Author: jinshaohui
> Mail: jinshaohui789@163.com
> Time: 18-10-12
> Desc:
************************************************************************/
#ifndef STACK_LINK_LIST_H
#define STACK_LINK_LIST_H
typedef struct _linkliststack
{
int data;
struct _linkliststack *next;
}linklist_stack;
#define stack_is_empty(liststack) (liststack->next == NULL)
#endif

View File

@ -0,0 +1,158 @@
/*************************************************************************
> File Name: array_queue.c
> Author: jinshaohui
> Mail: jinshaohui789@163.com
> Time: 18-10-12
> Desc:
************************************************************************/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"./array_queue.h"
array_queue * array_queue_create(int size)
{
array_queue * queue = NULL;
queue = (array_queue*)malloc(sizeof(array_queue));
if (queue == NULL)
{
return NULL;
}
queue->array = (int *)malloc(sizeof(int)*size);
if (queue->array == NULL)
{
free(queue);
return NULL;
}
queue->size = size;
queue->num = 0;
queue->head = 0;
queue->tail = 0;
return queue;
}
void array_queue_destory(array_queue *queue)
{
if (queue == NULL)
{
return;
}
if (queue->array != NULL)
{
free(queue->array);
}
free(queue);
return;
}
/*入队列 */
int array_queue_enqueue(array_queue *queue,int data)
{
/*队列为空,或者队列满时,返回-1*/
if ((queue == NULL) || (array_queue_is_full(queue)))
{
return -1;
}
queue->num++;
queue->array[queue->tail] = data;
queue->tail = (queue->tail + 1) % queue->size;
return 0;
}
/*出队列*/
int array_queue_dequeue(array_queue * queue,int *data)
{
/*队列为空,数据存储为空,队列为空时返回-1*/
if ((queue == NULL) || (data == NULL) || (array_queue_is_empty(queue)))
{
return -1;
}
*data = queue->array[queue->head];
queue->num--;
queue->head = (queue->head + 1) % queue->size;
return 0;
}
void array_queue_dump(array_queue *queue)
{
int i = 0;
int pos = 0;
if ((queue == NULL) || (array_queue_is_empty(queue)))
{
printf("\r\n queue is empty");
return;
}
printf("\r\n size:%d,num:%d,head:%d,tali:%d",
queue->size,queue->num,queue->head,queue->tail);
for (i = 0; i < queue->num; i ++)
{
pos = (queue->head + i) %queue->size;
printf("\r\n array[%d] = %d",pos,queue->array[pos]);
}
return;
}
int main()
{
int i = 0;
int ret = 0;
int data = 0;
array_queue * queue = NULL;
queue = array_queue_create(4);
if (queue == NULL)
{
printf("\r\n queue is create failed.");
return 0;
}
/*队列时空时,出队返回错误*/
ret = array_queue_dequeue(queue, &data);
if (ret != 0)
{
printf("\r\n queue %d dequeue failed.",ret);
}
/*队列大小是4入队5个最后一个报错*/
for (i = 0; i < 5; i++)
{
ret = array_queue_enqueue(queue,i);
if (ret != 0)
{
printf("\r\n queue %d enqueue failed.",i);
}
}
array_queue_dump(queue);
ret = array_queue_dequeue(queue, &data);
if (ret != 0)
{
printf("\r\n queue %d dequeue failed.",i);
}
printf("\r\n queue %d dequue.",data);
array_queue_dump(queue);
data = 5;
printf("\r\n queue %d enqueue.",data);
ret = array_queue_enqueue(queue,data);
if (ret != 0)
{
printf("\r\n queue %d enqueue failed.",data);
}
array_queue_dump(queue);
array_queue_destory(queue);
return 0;
}

View File

@ -0,0 +1,24 @@
/*************************************************************************
> File Name: array_queue.h
> Author: jinshaohui
> Mail: jinshaohui789@163.com
> Time: 18-10-12
> Desc:
************************************************************************/
#ifndef ARRAY_QUEUE_H
#define ARRAY_QUEUE_H
typedef struct _array_queue
{
int size;/*队列的大小*/
int num; /*当前存储数据的大小*/
int head;/*队列的头*/
int tail;/*队列的尾*/
int *array;/*数据存储区*/
}array_queue;
#define array_queue_is_empty(array_queue) (array_queue->num == 0)
#define array_queue_is_full(array_queue) ((array_queue->num) == (array_queue->size))
#endif

View File

@ -0,0 +1,171 @@
/*************************************************************************
> File Name: list_queue.c
> Author: jinshaohui
> Mail: jinshaohui789@163.com
> Time: 18-10-13
> Desc:
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"./list_queue.h"
/*创建队列头*/
list_queue *list_queue_create()
{
list_queue * queue = NULL;
queue = (list_queue *)malloc(sizeof(list_queue));
if(queue == NULL)
{
return NULL;
}
queue->num = 0;
queue->head = NULL;
queue->tail = NULL;
return queue;
}
void list_queue_destroy(list_queue*queue)
{
int i = 0;
int data = 0;
if ((queue == NULL) || (list_queue_is_empty(queue)))
{
return ;
}
while(!list_queue_is_empty(queue))
{
(void)list_queue_dequeue(queue,&data);
}
free(queue);
return;
}
int list_queue_enqueue(list_queue *queue,int data)
{
queue_node *ptmp = NULL;
if(queue == NULL)
{
return -1;
}
ptmp = (queue_node *)malloc(sizeof(queue_node));
if (ptmp == NULL)
{
return -1;
}
ptmp->data = data;
ptmp->next = NULL;
if (queue->head == NULL)
{
queue->head = ptmp;
}
else
{
queue->tail->next = ptmp;
}
queue->tail = ptmp;
queue->num++;
return 0;
}
/*出队*/
int list_queue_dequeue(list_queue *queue,int *data)
{
queue_node * ptmp = NULL;
if ((queue == NULL) || (data == NULL) || list_queue_is_empty(queue))
{
return -1;
}
*data = queue->head->data;
ptmp = queue->head;
queue->head = queue->head->next;
queue->num--;
if (queue->head == NULL)
{
queue->tail = NULL;
}
free(ptmp);
return 0;
}
void list_queue_dump(list_queue*queue)
{
int i = 0;
queue_node *ptmp = NULL;
if ((queue == NULL) || (list_queue_is_empty(queue)))
{
return;
}
ptmp = queue->head;
printf("\r\n----dump queue num = %d--------",queue->num);
while(ptmp != NULL)
{
printf("\r\nnode[%d] = %d",i,ptmp->data);
i++;
ptmp = ptmp->next;
}
printf("\r\n---------------------------------\r\n");
return;
}
int main()
{
int i = 0;
int data = 0;
int ret = 0;
list_queue * queue;
queue = list_queue_create();
if (queue == NULL)
{
printf("\r\nlist queue create falied..");
return 0;
}
for (i = 0; i < 5; i++)
{
(void)list_queue_enqueue(queue,i);
}
list_queue_dump(queue);
ret = list_queue_dequeue(queue,&data);
if(ret != 0)
{
printf("\r\nlist queue dequeue %d falied.",data);
}
printf("\r\nlist queue dequeue %d",data);
list_queue_dump(queue);
ret = list_queue_dequeue(queue,&data);
if(ret != 0)
{
printf("\r\nlist queue dequeue %d failed.",data);
}
printf("\r\nlist queue dequeue %d",data);
list_queue_dump(queue);
printf("\r\nlist queue enqueue %d",data);
(void)list_queue_enqueue(queue,data);
list_queue_dump(queue);
list_queue_destroy(queue);
return 0;
}

View File

@ -0,0 +1,27 @@
/*************************************************************************
> File Name: list_queue.h
> Author: jinshaohui
> Mail: jinshaohui789@163.com
> Time: 18-10-13
> Desc:
************************************************************************/
#ifndef LINK_LIST_QUEUE_H
#define LINK_LIST_QUEUE_H
typedef struct _list_queue_node
{
int data;
struct _list_queue_node *next;
}queue_node;
typedef struct _list_queue
{
int num;
queue_node *head;
queue_node *tail;
}list_queue;
#define list_queue_is_empty(queue) ((queue->num) == 0)
#endif

54
go/11_sorts/Sort.go Normal file
View File

@ -0,0 +1,54 @@
package _1_sorts
func BubbleSort(a []int) {
arrLen := len(a)
if arrLen <= 1 {
return
}
for i := arrLen - 1; i > 0; i-- {
for j := 0; j < i; j++ {
if a[j] > a[j+1] {
tmp := a[j+1]
a[j+1] = a[j]
a[j] = tmp
}
}
}
}
func InsertSort(a []int) {
arrLen := len(a)
if arrLen <= 1 {
return
}
for i := 1; i < arrLen; i++ {
v := a[i]
j := i - 1
for ; j >= 0; j-- {
if a[j] > v {
a[j+1] = a[j]
}
}
a[j+1] = v
}
}
func SelectionSort(a []int) {
arrLen := len(a)
if arrLen <= 1 {
return
}
for i := 0; i < arrLen; i++ {
minIndex := i
for j := i + 1; j < arrLen; j++ {
if a[j] < a[minIndex] {
minIndex = j
}
}
if minIndex != i {
tmp := a[minIndex]
a[minIndex] = a[i]
a[i] = tmp
}
}
}

43
go/11_sorts/Sort_test.go Normal file
View File

@ -0,0 +1,43 @@
package _1_sorts
import (
"testing"
)
func TestBubbleSort(t *testing.T) {
a := []int{5, 4, 3, 2, 1}
BubbleSort(a)
t.Log(a)
}
func TestSelectionSort(t *testing.T) {
a := []int{5, 4, 3, 2, 1}
SelectionSort(a)
t.Log(a)
}
func TestInsertSort(t *testing.T) {
a := []int{5, 4, 3, 2, 1}
InsertSort(a)
t.Log(a)
}
func BenchmarkBubbleSort(b *testing.B) {
a := []int{5, 4, 3, 2, 1}
for i := 0; i < b.N; i++ {
BubbleSort(a)
}
}
func BenchmarkSelectionSort(b *testing.B) {
a := []int{5, 4, 3, 2, 1}
for i := 0; i < b.N; i++ {
SelectionSort(a)
}
}
func BenchmarkInsertSort(b *testing.B) {
a := []int{5, 4, 3, 2, 1}
for i := 0; i < b.N; i++ {
InsertSort(a)
}
}

View File

@ -0,0 +1,164 @@
/**
*
* 1泛型动态数组
*
* Author: shi
*/
public class GenericArray<T> {
private T[] data;
private int size;
// 根据传入容量构造Array
public GenericArray(int capacity) {
data = (T[]) new Object[capacity];
size = 0;
}
// 无参构造方法默认数组容量为10
public GenericArray() {
this(10);
}
// 获取数组容量
public int getCapacity() {
return data.length;
}
// 获取当前元素个数
public int count() {
return size;
}
// 判断数组是否为空
public boolean isEmpty() {
return size == 0;
}
// 修改 index 位置的元素
public void set(int index, T e) {
checkIndex(index);
data[index] = e;
}
// 获取对应 index 位置的元素
public T get(int index) {
checkIndex(index);
return data[index];
}
// 查看数组是否包含元素e
public boolean contains(T e) {
for (int i = 0; i < size; i++) {
if (data[i].equals(e)) {
return true;
}
}
return false;
}
// 获取对应元素的下标, 未找到返回 -1
public int find(T e) {
for ( int i = 0; i < size; i++) {
if (data[i].equals(e)) {
return i;
}
}
return -1;
}
// index 位置插入元素e, 时间复杂度 O(m+n)
public void add(int index, T e) {
checkIndex(index);
// 如果当前元素个数等于数组容量则将数组扩容为原来的2倍
if (size == data.length) {
resize(2 * data.length);
}
for (int i = size - 1; i >= index; i--) {
data[i + 1] = data[i];
}
data[index] = e;
size++;
}
// 向数组头插入元素
public void addFirst(T e) {
add(0, e);
}
// 向数组尾插入元素
public void addLast(T e) {
add(size, e);
}
// 删除 index 位置的元素并返回
public T remove(int index) {
checkIndex(index);
T ret = data[index];
for (int i = index + 1; i < size; i++) {
data[i - 1] = data[i];
}
size --;
data[size] = null;
// 缩容
if (size == data.length / 4 && data.length / 2 != 0) {
resize(data.length / 2);
}
return ret;
}
// 删除第一个元素
public T removeFirst() {
return remove(0);
}
// 删除末尾元素
public T removeLast() {
return remove(size - 1);
}
// 从数组中删除指定元素
public void removeElement(T e) {
int index = find(e);
if (index != -1) {
remove(index);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(String.format("Array size = %d, capacity = %d \n", size, data.length));
builder.append('[');
for (int i = 0; i < size; i++) {
builder.append(data[i]);
if (i != size - 1) {
builder.append(", ");
}
}
builder.append(']');
return builder.toString();
}
// 扩容方法时间复杂度 O(n)
private void resize(int capacity) {
T[] newData = (T[]) new Object[capacity];
for (int i = 0; i < size; i++) {
newData[i] = data[i];
}
data = newData;
}
private void checkIndex(int index) {
if (index < 0 || index > size) {
throw new IllegalArgumentException("Add failed! Require index >=0 and index <= size.");
}
}
}

View File

@ -5,6 +5,7 @@ package array;
* 2数组中的数据是int类型的 * 2数组中的数据是int类型的
* *
* Author: Zheng * Author: Zheng
* modify: xing
*/ */
public class Array { public class Array {
//定义整型数据data保存数据 //定义整型数据data保存数据
@ -27,6 +28,35 @@ public class Array {
return data[index]; return data[index];
} }
//插入元素:头部插入尾部插入
public boolean insert(int index, int value){
//数组中无元素
//if (index == count && count == 0) {
// data[index] = value;
// ++count;
// return true;
//}
// 数组空间已满
if (count == n) {
System.out.println("没有可插入的位置");
return false;
}
// 如果count还没满那么就可以插入数据到数组中
// 位置不合法
if (index < 0||index > count ) {
System.out.println("位置不合法");
return false;
}
// 位置合法
for( int i = count; i > index; --i){
data[i] = data[i - 1];
}
data[index] = value;
++count;
return true;
}
//根据索引删除数组中元素 //根据索引删除数组中元素
public boolean delete(int index){ public boolean delete(int index){
if (index<0 || index >=count) return false; if (index<0 || index >=count) return false;
@ -45,41 +75,6 @@ public class Array {
--count; --count;
return true; return true;
} }
//向数组中插入一个元素
public boolean insert(int index, int value){
if (index<0 || index>=count) return false;
//当实际存储的个数等于数组的最大长度就不让新增
if (count == n) return false;
//数组长度增加1不需要初始化
/*int[] arr = new int[count+1];
for (int i = 0; i < data.length; i++) {
arr[i] = data[i];
}
data=arr;*/
for (int i = count-1; i>=index; --i){
data[i+1] = data[i];
}
data[index] = value;
++count;
return true;
}
public boolean insertToTail(int value) {
//当实际存储的个数等于数组的最大长度就不让新增
if (count == n) return false;
//数组长度增加1
/*int[] arr = new int[count+1];
for (int i = 0; i < data.length; i++) {
arr[i] = data[i];
}
data=arr;*/
data[count++] = value;
return true;
}
public void printAll() { public void printAll() {
for (int i = 0; i < count; ++i) { for (int i = 0; i < count; ++i) {
System.out.print(data[i] + " "); System.out.print(data[i] + " ");
@ -87,6 +82,17 @@ public class Array {
System.out.println(); System.out.println();
} }
public static void main(String[] args) {
ArrayOperate array = new ArrayOperate(5);
array.printAll();
array.insert(0, 3);
array.insert(0, 4);
array.insert(1, 5);
array.insert(3, 9);
array.insert(3, 10);
//array.insert(3, 11);
array.printAll();
}
} }

View File

@ -49,13 +49,11 @@ public class Sorts {
// 选择排序a表示数组n表示数组大小 // 选择排序a表示数组n表示数组大小
public static void selectionSort(int[] a, int n) { public static void selectionSort(int[] a, int n) {
if (n <= 1) return; if (n <= 1) return;
for (int i = 0; i < n; ++i) { for (int i = 0; i < n - 1; ++i) {
// 查找最小值 // 查找最小值
int minIndex = i; int minIndex = i;
int minValue = a[i]; for (int j = i + 1; j < n; ++j) {
for (int j = i; j < n; ++j) { if (a[j] < a[minIndex]) {
if (a[j] < minValue) {
minValue = a[j];
minIndex = j; minIndex = j;
} }
} }

View File

@ -0,0 +1,100 @@
package sorts;
/**
* 向下冒泡算法 或许比冒泡更易懂的排序算法
* 希尔排序
*
* Author: wliu
*/
public class SortsAddOn {
public static void main(String[] args) {
int[] arr = {3, 2, 6, 4, 5, 1, 9, 20, 13, 16};
// bubbleDownSort(arr);
shellSort(arr);
print(arr);
}
/**
* 向下冒泡可能比冒泡更易懂
*
* 算法概要
* 从0开始用这个元素去跟后面的所有元素比较如果发现这个元素大于后面的某个元素则交换
* 3 2 6 4 5 1
* 第一趟是从 index=0 也就是 3 开始跟index=1及其后面的数字比较
* 3 大于 2交换变为 2 3 6 4 5 1此时index=0的位置变为了2
* 接下来将用2跟index=2比较
* 2 不大于 6 不交换
* 2 不大于 4 不交换
* 2 不大于 5 不交换
* 2 大于 1交换变为 1 3 6 4 5 2第一趟排序完成
*
* 第二趟是从 index=1 也就是 3开始跟index=2及其后面的数字比较
* 3 不大于 6 不交换
* 3 不大于 4 不交换
* 3 不大于 5 不交换
* 3 大于 2交换变为 1 2 6 4 5 3第二趟排序完成
*
* 第三趟是从 index=2 也就是 6开始跟index=3及其后面的数字比较
* 6 大于 4交换变为 1 2 4 6 5 3, 此时 index = 2 的位置变为了4
* 接下来将用4跟index=4比较
* 4 不大于 5 不交换
* 4 大于 3交换变为 1 2 3 6 5 4第三趟排序完成
*
* 第四趟是从 index=3 也就是 6开始跟index=4及其后面的数字比较
* 6 大于 5交换变为 1 2 3 5 6 4, 此时 index = 3 的位置变为了5
* 接下来将用5跟index=5比较
* 5 大于 4交换变为 1 2 3 4 6 5, 第四趟排序完成
*
* 第五趟是从 index=4 也就是 6开始跟index=5及其后面的数字比较
* 6 大于 5交换变为 1 2 3 4 5 6, 此时 index = 4 的位置变为了5
* 接下来将用5跟index=6比较
* index = 6 已经不满足 index < length 的条件整个排序完成
*/
private static void bubbleDownSort(int[] arr) {
int len = arr.length;
if (len == 1) return;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (arr[i] > arr[j]) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
private static void shellSort(int[] arr) {
int len = arr.length;
if (len == 1) return;
int step = len / 2;
while (step >= 1) {
for (int i = step; i < len; i++) {
int value = arr[i];
int j = i - step;
for (; j >= 0; j -= step) {
if (value < arr[j]) {
arr[j+step] = arr[j];
} else {
break;
}
}
arr[j+step] = value;
}
step = step / 2;
}
}
private static void print(int[] arr) {
System.out.println("Print array:");
for (int x : arr) {
System.out.print(x + "\t");
}
System.out.println("");
}
}

2
php/.gitignore vendored
View File

@ -1,2 +1,4 @@
.idea .idea
vendor vendor
*my*
Queue

View File

@ -28,6 +28,14 @@ function expression($str)
array_push($operStack, $arr[$i]); array_push($operStack, $arr[$i]);
break; break;
case '*': case '*':
$arrLen = count($operStack);
while ($operStack[$arrLen-1] === '/'){
compute($numStack, $operStack);
$arrLen--;
}
array_push($operStack, $arr[$i]);
break;
case '/': case '/':
case '(': case '(':
array_push($operStack, $arr[$i]); array_push($operStack, $arr[$i]);
@ -70,7 +78,9 @@ function compute(&$numStack, &$operStack){
case '-': case '-':
array_push($numStack, array_pop($numStack) - $num); array_push($numStack, array_pop($numStack) - $num);
break; break;
case '(':
throw new \Exception("不匹配的(", 2);
break;
} }
} }
expression('-1+2-(1+2*3)'); expression('-1+2-(1+2*3)');

View File

@ -0,0 +1,115 @@
<?php
/**
* User: Hkesd
* Date: 2018/10/13 11:26
* Desc:
*/
namespace Algo_09;
use Algo_06\SingleLinkedListNode;
/**
* 队列 链表实现
*
* Class QueueOnLinkedList
*/
class QueueOnLinkedList
{
/**
* 队列头节点
*
* @var SingleLinkedListNode
*/
public $head;
/**
* 队列尾节点
*
* @var null
*/
public $tail;
/**
* 队列长度
*
* @var int
*/
public $length;
/**
* QueueOnLinkedList constructor.
*/
public function __construct()
{
$this->head = new SingleLinkedListNode();
$this->tail = $this->head;
$this->length = 0;
}
/**
* 入队
*
* @param $data
*/
public function enqueue($data)
{
$newNode = new SingleLinkedListNode();
$newNode->data = $data;
$this->tail->next = $newNode;
$this->tail = $newNode;
$this->length++;
}
/**
* 出队
*
* @return SingleLinkedListNode|bool|null
*/
public function dequeue()
{
if (0 == $this->length) {
return false;
}
$node = $this->head->next;
$this->head->next = $this->head->next->next;
$this->length--;
return $node;
}
/**
* 获取队列长度
*
* @return int
*/
public function getLength()
{
return $this->length;
}
/**
* 打印队列
*/
public function printSelf()
{
if (0 == $this->length) {
echo 'empty queue' . PHP_EOL;
return;
}
echo 'head.next -> ';
$curNode = $this->head;
while ($curNode->next) {
echo $curNode->next->data . ' -> ';
$curNode = $curNode->next;
}
echo 'NULL' . PHP_EOL;
}
}

View File

@ -0,0 +1,60 @@
<?php
class LoopQueue
{
private $MaxSzie;
private $data = [];
private $head = 0;
private $tail = 0;
/**
* 初始化队列大小 最后的位置不存放数据,实际大小 = size++
*/
public function __construct($size = 10)
{
$this->MaxSzie = ++$size;
}
/**
* 队列满条件 ($this->tail+1) % $this->MaxSzie == $this->head
*/
public function enQueue($data)
{
if (($this->tail+1) % $this->MaxSzie == $this->head)
return -1;
$this->data[$this->tail] = $data;
$this->tail = (++$this->tail) % $this->MaxSzie;
}
public function deQueue()
{
if ($this->head == $this->tail)
return NULL;
$data = $this->data[$this->head];
unset($this->data[$this->head]);
$this->head = (++$this->head) % $this->MaxSzie;
return $data;
}
public function getLength()
{
return ($this->tail - $this->head + $this->MaxSzie) % $this->MaxSzie;
}
}
$queue = new LoopQueue(4);
// var_dump($queue);
$queue->enQueue(1);
$queue->enQueue(2);
$queue->enQueue(3);
$queue->enQueue(4);
// $queue->enQueue(5);
var_dump($queue->getLength());
$queue->deQueue();
$queue->deQueue();
$queue->deQueue();
$queue->deQueue();
$queue->deQueue();
var_dump($queue);

29
php/09_queue/main.php Normal file
View File

@ -0,0 +1,29 @@
<?php
/**
* User: Hkesd
* Date: 2018/10/13 11:46
* Desc:
*/
namespace Algo_09;
require_once "../vendor/autoload.php";
$queue = new QueueOnLinkedList();
$queue->enqueue(1);
$queue->enqueue(2);
$queue->enqueue(3);
$queue->enqueue(4);
$queue->enqueue(5);
$queue->printSelf();
var_dump($queue->getLength());
$queue->dequeue();
$queue->printSelf();
$queue->dequeue();
$queue->dequeue();
$queue->dequeue();
$queue->printSelf();
$queue->dequeue();
$queue->printSelf();

24
php/11_sort/Sort.php Normal file
View File

@ -0,0 +1,24 @@
<?php
function insertSort(&$arr)
{
$i = 0;
$len = count($arr);
while($i < $len){
$data = $arr[$i+1];
for ($j = $i;$j >=0 ;$j-- ){
if ($data >= $arr[$j]){
array_splice($arr, $i+1, 1);
array_splice($arr, ++$j, 0, $data);
break;
}
}
$i++;
}
}
$arr = [1,4,6,2,3,5,4];
insertSort($arr);
var_dump($arr);

View File

@ -17,4 +17,7 @@
* findMiddleNode 求链表的中间结点 * findMiddleNode 求链表的中间结点
#### 08_stack #### 08_stack
* 链栈实现 * 链栈实现
#### 09_stack
* 队列链表实现

View File

@ -7,7 +7,8 @@
"psr-4": { "psr-4": {
"Algo_06\\": "06_linkedlist/", "Algo_06\\": "06_linkedlist/",
"Algo_07\\": "07_linkedlist/", "Algo_07\\": "07_linkedlist/",
"Algo_08\\": "08_stack/" "Algo_08\\": "08_stack/",
"Algo_09\\": "09_queue/"
} }
} }
} }

95
python/11_sorts/sorts.py Normal file
View File

@ -0,0 +1,95 @@
"""
Bubble sort, insertion sort and selection sort
冒泡排序插入排序选择排序
Author: Wenru
"""
from typing import List
# 冒泡排序
def bubble_sort(a: List[int]):
if len(a) <= 1: return
made_swap = False
for i in range(len(a)):
for j in range(len(a) - i - 1):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
made_swap = True
if not made_swap: break
# 插入排序
def insertion_sort(a: List[int]):
if len(a) <= 1: return
for i in range(1, len(a)):
value = a[i]
j = i - 1
while j >= 0 and a[j] > value:
a[j+1] = a[j]
j -= 1
a[j+1] = value
# 选择排序
def selection_sort(a: List[int]):
if len(a) <= 1: return
for i in range(len(a)):
min_index = i
min_val = a[i]
for j in range(i, len(a)):
if a[j] < min_val:
min_val = a[j]
min_index = j
a[i], a[min_index] = a[min_index], a[i]
if __name__ == "__main__":
array = [1, 1, 1, 1]
bubble_sort(array)
print(array)
array = [1, 2, 3, 4]
bubble_sort(array)
print(array)
array = [4, 3, 2, 1]
bubble_sort(array)
print(array)
array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
bubble_sort(array)
print(array)
array = [1, 1, 1, 1]
insertion_sort(array)
print(array)
array = [1, 2, 3, 4]
insertion_sort(array)
print(array)
array = [4, 3, 2, 1]
insertion_sort(array)
print(array)
array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
insertion_sort(array)
print(array)
array = [1, 1, 1, 1]
selection_sort(array)
print(array)
array = [1, 2, 3, 4]
selection_sort(array)
print(array)
array = [4, 3, 2, 1]
selection_sort(array)
print(array)
array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
selection_sort(array)
print(array)

View File

@ -0,0 +1,81 @@
import Foundation
///
///
/// - Parameter elements:
/// - Returns:
public func bubbleSort<T>(_ elements: [T]) ->[T] where T: Comparable {
var array = elements
guard array.count > 1 else {
return array
}
for i in 0..<array.count {
// 退
var flag = false
for j in 0..<array.count - i - 1 {
if array[j] > array[j+1] {
array.swapAt(j+1, j)
//
flag = true
}
}
if (!flag) {
break
}
}
return array
}
///
///
/// - Parameter elements:
/// - Returns:
public func insertionSort<T>(_ elements: [T]) -> [T] where T: Comparable {
var array = elements
guard array.count > 1 else {
return array
}
for i in 1..<array.count {
let value = array[i]
var j = i - 1;
//
for p in (0...j).reversed() {
j = p
if array[p] > value {
array[p+1] = array[p]
} else {
break
}
}
array[j+1] = value
}
return array
}
///
///
/// - Parameter elements:
/// - Returns:
public func selectionSort<T>(_ elements: [T]) -> [T] where T: Comparable {
var array = elements
guard array.count > 1 else {
return array
}
for i in 0..<array.count {
//
var minIndex = i
var minValue = array[i]
for j in i..<array.count {
if array[j] < minValue {
minValue = array[j]
minIndex = j
}
}
//
array.swapAt(i, minIndex)
}
return array
}