赞
踩
- dataType[] arrayRefVar; //首选的方法
- // 或
- dataType arrayRefVar[]; //效果相同,但不是首选方法
dataType[ ] arrayRefVar = new dataType[ arraySize];
- int[] a = {1,2,3};
- Man[ ] mans = {new Man(1,1),new Man(2,2)};
- int[] a = new int[2];
- a[0]=1;
- a[1]=2;
- java.lang.Object
- |java.util.AbstractCollection<E>
- |java.util.AbstractList<E>
- |java.util.ArrayList<E>
- public class ArrayList<E> extends AbstractList<E>
- implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
- //可序列化版本号
- private static final long serialVersionUID = 8683452581122892189L;
-
- //默认的初始化数组大小 为10 .
- private static final int DEFAULT_CAPACITY = 10;
-
- //实例化一个空数组
- private static final Object[] EMPTY_ELEMENTDATA = {};
-
- //存放List元素的数组
- private transient Object[] elementData;
-
- //List中元素的数量,和存放List元素的数组长度可能相等,也可能不相等
- private int size;
-
- //构造方法,指定初始化的数组长度
- public ArrayList(int initialCapacity) {
- super();
- if (initialCapacity < 0)
- throw new IllegalArgumentException("Illegal Capacity: "+
- initialCapacity);
- this.elementData = new Object[initialCapacity];
- }
-
- //无参构造方法
- public ArrayList() {
- super();
- this.elementData = EMPTY_ELEMENTDATA;
- }
-
- //构造方法,参数为集合元素
- public ArrayList(Collection<? extends E> c) {
- //将集合转换成数组,并赋值给elementData数组
- elementData = c.toArray();
- size = elementData.length;
- //如果c.toArray返回的不是Object[]类型的数组,转换成Object[]类型
- if (elementData.getClass() != Object[].class)
- elementData = Arrays.copyOf(elementData, size, Object[].class);
- }
-
- //改变数组的长度,使长度和List的size相等。
- public void trimToSize() {
- modCount++;
- if (size < elementData.length) {
- elementData = Arrays.copyOf(elementData, size);
- }
- }
-
- //确定ArrayList的容量
- //判断当前elementData是否是EMPTY_ELEMENTDATA,若是设置长度为10
- public void ensureCapacity(int minCapacity) {
- int minExpand = (elementData != EMPTY_ELEMENTDATA)
- // any size if real element table
- ? 0
- // larger than default for empty table. It's already supposed to be
- // at default size.
- : DEFAULT_CAPACITY;
- //是否需要扩容
- if (minCapacity > minExpand) {
- ensureExplicitCapacity(minCapacity);
- }
- }
- //当前位置和默认大小之间取最大值
- private void ensureCapacityInternal(int minCapacity) {
- if (elementData == EMPTY_ELEMENTDATA) {
- minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
- }
-
- ensureExplicitCapacity(minCapacity);
- }
-
- private void ensureExplicitCapacity(int minCapacity) {
- modCount++;
-
- // overflow-conscious code
- if (minCapacity - elementData.length > 0)
- grow(minCapacity);
- }
-
- //数组的最大容量
- private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
-
- //扩容操作
- private void grow(int minCapacity) {
- // overflow-conscious code
- int oldCapacity = elementData.length;
- //容量扩充1.5倍
- int newCapacity = oldCapacity + (oldCapacity >> 1);
- if (newCapacity - minCapacity < 0)
- newCapacity = minCapacity;
- if (newCapacity - MAX_ARRAY_SIZE > 0)
- newCapacity = hugeCapacity(minCapacity);
- // minCapacity is usually close to size, so this is a win:
- //生成一个长度为newCapacity数组,并将elementData数组中元素拷贝到新数组中,并将新数组的引用赋值给elementData
- elementData = Arrays.copyOf(elementData, newCapacity);
- }
-
- private static int hugeCapacity(int minCapacity) {
- if (minCapacity < 0) // overflow
- throw new OutOfMemoryError();
- return (minCapacity > MAX_ARRAY_SIZE) ?
- Integer.MAX_VALUE :
- MAX_ARRAY_SIZE;
- }
-
- //返回数组中已经放入的元素个数,非数组长度
- public int size() {
- return size;
- }
-
- //List是否为空
- public boolean isEmpty() {
- return size == 0;
- }
-
- //判断是否包包含指定元素
- public boolean contains(Object o) {
- return indexOf(o) >= 0;
- }
-
- //查找指定的元素,存在返回下标,不存在放回 -1
- public int indexOf(Object o) {
- if (o == null) {
- for (int i = 0; i < size; i++)
- if (elementData[i]==null)
- return i;
- } else {
- for (int i = 0; i < size; i++)
- if (o.equals(elementData[i]))
- return i;
- }
- return -1;
- }
-
- //倒序查找元素,存在放回下标,不存在返回-1
- public int lastIndexOf(Object o) {
- if (o == null) {
- for (int i = size-1; i >= 0; i--)
- if (elementData[i]==null)
- return i;
- } else {
- for (int i = size-1; i >= 0; i--)
- if (o.equals(elementData[i]))
- return i;
- }
- return -1;
- }
-
- //因为实现了clone接口,所以需要重写clone()方法,实现对象的拷贝
- public Object clone() {
- try {
- @SuppressWarnings("unchecked")
- ArrayList<E> v = (ArrayList<E>) super.clone();
- v.elementData = Arrays.copyOf(elementData, size);
- v.modCount = 0;
- return v;
- } catch (CloneNotSupportedException e) {
- // this shouldn't happen, since we are Cloneable
- throw new InternalError();
- }
- }
-
- //将集合转化为数组
- public Object[] toArray() {
- return Arrays.copyOf(elementData, size);
- }
-
- //转化为指定类型的数组元素,推荐使用此方法
- @SuppressWarnings("unchecked")
- public <T> T[] toArray(T[] a) {
- if (a.length < size)
- // Make a new array of a's runtime type, but my contents:
- return (T[]) Arrays.copyOf(elementData, size, a.getClass());
- System.arraycopy(elementData, 0, a, 0, size);
- if (a.length > size)
- a[size] = null;
- return a;
- }
-
- // Positional Access Operations
- //放回指定位置的数组元素
- @SuppressWarnings("unchecked")
- E elementData(int index) {
- return (E) elementData[index];
- }
-
- //返回列表中指定位置的元素
- public E get(int index) {
- rangeCheck(index);
-
- return elementData(index);
- }
-
- //设置指定位置的元素,并返回被替换的元素
- public E set(int index, E element) {
- rangeCheck(index);
-
- E oldValue = elementData(index);
- elementData[index] = element;
- return oldValue;
- }
-
- //添加元素
- public boolean add(E e) {
- ensureCapacityInternal(size + 1); // Increments modCount!!
- elementData[size++] = e;
- return true;
- }
- //将元素添加到指定位置上,从指定位置的元素开始所有元素向后移动,为新添加的元素提供位置
- public void add(int index, E element) {
- rangeCheckForAdd(index);
-
- ensureCapacityInternal(size + 1); // Increments modCount!!
- System.arraycopy(elementData, index, elementData, index + 1,
- size - index);
- elementData[index] = element;
- size++;
- }
-
- //删除指定位置的元素,其他元素做相依的移动,并将最后一个元素置空,方便垃圾处理机制回收,防止内存泄露,并返回删除的元素值
- public E remove(int index) {
- rangeCheck(index);
-
- modCount++;
- E oldValue = elementData(index);
-
- int numMoved = size - index - 1;
- if (numMoved > 0)
- System.arraycopy(elementData, index+1, elementData, index,
- numMoved);
- elementData[--size] = null; // clear to let GC do its work
-
- return oldValue;
- }
-
- //删除元素方法
- public boolean remove(Object o) {
- if (o == null) {
- for (int index = 0; index < size; index++)
- if (elementData[index] == null) {
- fastRemove(index);
- return true;
- }
- } else {
- for (int index = 0; index < size; index++)
- if (o.equals(elementData[index])) {
- fastRemove(index);
- return true;
- }
- }
- return false;
- }
-
- //快速删除执行操作
- private void fastRemove(int index) {
- modCount++;
- int numMoved = size - index - 1;
- if (numMoved > 0)
- System.arraycopy(elementData, index+1, elementData, index,
- numMoved);
- elementData[--size] = null; // clear to let GC do its work
- }
-
- //清除列表
- public void clear() {
- modCount++;
-
- // clear to let GC do its work
- for (int i = 0; i < size; i++)
- elementData[i] = null;
-
- size = 0;
- }
-
- //添加方法,添加的元素为集合
- public boolean addAll(Collection<? extends E> c) {
- Object[] a = c.toArray();
- int numNew = a.length;
- ensureCapacityInternal(size + numNew); // Increments modCount
- System.arraycopy(a, 0, elementData, size, numNew);
- size += numNew;
- return numNew != 0;
- }
-
- //从指定位置开始添加集合元素
- public boolean addAll(int index, Collection<? extends E> c) {
- rangeCheckForAdd(index);
-
- Object[] a = c.toArray();
- int numNew = a.length;
- ensureCapacityInternal(size + numNew); // Increments modCount
-
- int numMoved = size - index;
- if (numMoved > 0)
- System.arraycopy(elementData, index, elementData, index + numNew,
- numMoved);
-
- System.arraycopy(a, 0, elementData, index, numNew);
- size += numNew;
- return numNew != 0;
- }
-
- //范围删除方法
- protected void removeRange(int fromIndex, int toIndex) {
- modCount++;
- int numMoved = size - toIndex;
- System.arraycopy(elementData, toIndex, elementData, fromIndex,
- numMoved);
-
- // clear to let GC do its work
- int newSize = size - (toIndex-fromIndex);
- for (int i = newSize; i < size; i++) {
- elementData[i] = null;
- }
- size = newSize;
- }
-
- //下标检测方法,如果不合法,抛出IndexOutOfBoundsException异常
- private void rangeCheck(int index) {
- if (index >= size)
- throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
- }
-
- /**
- * A version of rangeCheck used by add and addAll.
- */
- private void rangeCheckForAdd(int index) {
- if (index > size || index < 0)
- throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
- }
-
- //溢出信息
- private String outOfBoundsMsg(int index) {
- return "Index: "+index+", Size: "+size;
- }
-
- //删除所有元素
- public boolean removeAll(Collection<?> c) {
- return batchRemove(c, false);
- }
-
-
- public boolean retainAll(Collection<?> c) {
- return batchRemove(c, true);
- }
-
- private boolean batchRemove(Collection<?> c, boolean complement) {
- final Object[] elementData = this.elementData;
- int r = 0, w = 0;
- boolean modified = false;
- try {
- for (; r < size; r++)
- if (c.contains(elementData[r]) == complement)
- elementData[w++] = elementData[r];
- } finally {
- // Preserve behavioral compatibility with AbstractCollection,
- // even if c.contains() throws.
- if (r != size) {
- System.arraycopy(elementData, r,
- elementData, w,
- size - r);
- w += size - r;
- }
- if (w != size) {
- // clear to let GC do its work
- for (int i = w; i < size; i++)
- elementData[i] = null;
- modCount += size - w;
- size = w;
- modified = true;
- }
- }
- return modified;
- }
- //流操作方法,将对象写入输出流中
- private void writeObject(java.io.ObjectOutputStream s)
- throws java.io.IOException{
- // Write out element count, and any hidden stuff
- int expectedModCount = modCount;
- s.defaultWriteObject();
-
- // Write out size as capacity for behavioural compatibility with clone()
- s.writeInt(size);
-
- // Write out all elements in the proper order.
- for (int i=0; i<size; i++) {
- s.writeObject(elementData[i]);
- }
-
- if (modCount != expectedModCount) {
- throw new ConcurrentModificationException();
- }
- }
-
- //流操作,读方法,将对象从流中取出
- private void readObject(java.io.ObjectInputStream s)
- throws java.io.IOException, ClassNotFoundException {
- elementData = EMPTY_ELEMENTDATA;
-
- // Read in size, and any hidden stuff
- s.defaultReadObject();
-
- // Read in capacity
- s.readInt(); // ignored
-
- if (size > 0) {
- // be like clone(), allocate array based upon size not capacity
- ensureCapacityInternal(size);
-
- Object[] a = elementData;
- // Read in all elements in the proper order.
- for (int i=0; i<size; i++) {
- a[i] = s.readObject();
- }
- }
- }
-
- //迭代方法,返回内部类实例
- public ListIterator<E> listIterator(int index) {
- if (index < 0 || index > size)
- throw new IndexOutOfBoundsException("Index: "+index);
- return new ListItr(index);
- }
-
- //迭代方法,返回内部类实例
- public ListIterator<E> listIterator() {
- return new ListItr(0);
- }
-
- //迭代方法,返回内部类实例
- public Iterator<E> iterator() {
- return new Itr();
- }
-
- //内部类,实现Iterator接口
- private class Itr implements Iterator<E> {
- int cursor; // index of next element to return
- int lastRet = -1; // index of last element returned; -1 if no such
- int expectedModCount = modCount;
- //是否还有下一个元素,返回true or false
- public boolean hasNext() {
- return cursor != size;
- }
- //返回元素
- @SuppressWarnings("unchecked")
- public E next() {
- checkForComodification();
- int i = cursor;
- if (i >= size)
- throw new NoSuchElementException();
- Object[] elementData = ArrayList.this.elementData; //获取外部类的elementData数组
- if (i >= elementData.length)
- throw new ConcurrentModificationException();
- cursor = i + 1;
- return (E) elementData[lastRet = i];
- }
- //删除元素
- public void remove() {
- if (lastRet < 0)
- throw new IllegalStateException();
- checkForComodification();
-
- try {
- ArrayList.this.remove(lastRet); //调用外部类删除方法,删除指定位置的元素
- cursor = lastRet;
- lastRet = -1;
- expectedModCount = modCount;
- } catch (IndexOutOfBoundsException ex) {
- throw new ConcurrentModificationException();
- }
- }
-
- final void checkForComodification() {
- if (modCount != expectedModCount)
- throw new ConcurrentModificationException();
- }
- }
-
- //省略了ListItr、SubList两个内部类
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- ArrayList(int initialCapacity);
- ArrayList();
- ArrayList(Collection<? extends E> c);
- public boolean add(E e) {
- // 关键 -> 添加之前,校验容量
- ensureCapacityInternal(size + 1);
-
- // 修改 size,并在数组末尾添加指定元素
- elementData[size++] = e;
- return true;
- }
-
- // 关键 -> minCapacity = size+1,即表示执行完添加操作后,数组中的元素个数
- private void ensureCapacityInternal(int minCapacity) {
- // 判断内部数组是否为空
- if (elementData == EMPTY_ELEMENTDATA) {
- // 设置数组最小容量(>=10)
- minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
- }
- ensureExplicitCapacity(minCapacity);
- }
- //接着会判断添加操作会不会导致内部数组的容量饱和
- private void ensureExplicitCapacity(int minCapacity) {
- modCount++;
-
- // 判断结果为 true,则表示接下来的添加操作会导致元素数量超出数组容量
- if (minCapacity - elementData.length > 0){
- // 真正的扩容操作
- grow(minCapacity);
- }
- }
-
-
- //实现真正的扩容公式与数组的拷贝
- private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
-
- private void grow(int minCapacity) {
-
- int oldCapacity = elementData.length;
-
- // 关键-> 容量扩充公式
- int newCapacity = oldCapacity + (oldCapacity >> 1);
-
- // 针对新容量的一系列判断
- if (newCapacity - minCapacity < 0){
- newCapacity = minCapacity;
- }
- if (newCapacity - MAX_ARRAY_SIZE > 0){
- newCapacity = hugeCapacity(minCapacity);
- }
-
- // 关键 -> 复制旧数组元素到新数组中去
- elementData = Arrays.copyOf(elementData, newCapacity);
- }
-
- private static int hugeCapacity(int minCapacity) {
- if (minCapacity < 0){
- throw new OutOfMemoryError();
- }
-
- return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public static int binarySearch(Integer[] srcArray, int des) {
- //定义初始最小、最大索引
- int start = 0;
- int end = srcArray.length - 1;
- //确保不会出现重复查找,越界
- while (start <= end) {
- //计算出中间索引值
- int middle = (end + start)>>>1 ;//防止溢出
- if (des == srcArray[middle]) {
- return middle;
- //判断下限
- } else if (des < srcArray[middle]) {
- end = middle - 1;
- //判断上限
- } else {
- start = middle + 1;
- }
- }
- //若没有,则返回-1
- return -1;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public int[] bubbleSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- for (int i = 0; i < array.length - 1; i++) {
- boolean flag = false;
- for (int j = 0; j < array.length - 1 - i; j++) {
- if (array[j] > array[j + 1]) {
- //这里交换两个数据并没有使用中间变量,而是使用异或的方式来实现
- array[j] = array[j] ^ array[j + 1];
- array[j + 1] = array[j] ^ array[j + 1];
- array[j] = array[j] ^ array[j + 1];
-
- flag = true;
- }
- }
- if (!flag) {
- break;
- }
- }
- return array;
- }
-
-
- public class Demo {
-
- public static void main(String[] args) {
- int[] a = {7, 3, 5, 9, 4, 6, 8, 2, 1};
- int iTmp = 0;
- for(int i=0; i<a.length; i++) {
- for(int j=0; j<a.length-i-1; j++) {
- if(a[j] > a[j+1]) {
- iTmp = a[j];
- a[j] = a[j+1];
- a[j+1] = iTmp;
- }
- }
- }
-
- for(int i=0; i<a.length; i++) {
- System.out.println(a[i]);
- }
- }
-
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public int[] selectSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- for (int i = 0; i < array.length - 1; i++) {
- int minIndex = i;
- for (int j = i + 1; j < array.length; j++) {
- if (array[j] < array[minIndex]) {
- minIndex = j;
- }
- }
- if (minIndex > i) {
- array[i] = array[i] ^ array[minIndex];
- array[minIndex] = array[i] ^ array[minIndex];
- array[i] = array[i] ^ array[minIndex];
- }
- }
- return array;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public int[] insertSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- for (int i = 1; i < array.length; i++) {
- int temp = array[i];
- int j = i - 1;
- while (j >= 0 && array[j] > temp) {
- array[j + 1] = array[j];
- j--;
- }
- array[j + 1] = temp;
- }
- return array;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public int[] shellSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- int gap = array.length >>> 1;
- while (gap > 0) {
- for (int i = gap; i < array.length; i++) {
- int temp = array[i];
- int j = i - gap;
- while (j >= 0 && array[j] > temp) {
- array[j + gap] = array[j];
- j = j - gap;
- }
- array[j + gap] = temp;
- }
- gap >>>= 1;
- }
- return array;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public class MaxHeap {
-
- /**
- * 排序数组
- */
- private int[] nodeArray;
- /**
- * 数组的真实大小
- */
- private int size;
-
- private int parent(int index) {
- return (index - 1) >>> 1;
- }
-
- private int leftChild(int index) {
- return (index << 1) + 1;
- }
-
- private int rightChild(int index) {
- return (index << 1) + 2;
- }
-
- private void swap(int i, int j) {
- nodeArray[i] = nodeArray[i] ^ nodeArray[j];
- nodeArray[j] = nodeArray[i] ^ nodeArray[j];
- nodeArray[i] = nodeArray[i] ^ nodeArray[j];
- }
-
- private void siftUp(int index) {
- //如果index处节点的值大于其父节点的值,则交换两个节点值,同时将index指向其父节点,继续向上循环判断
- while (index > 0 && nodeArray[index] > nodeArray[parent(index)]) {
- swap(index, parent(index));
- index = parent(index);
- }
- }
-
- private void siftDown(int index) {
- //左孩子的索引比size小,意味着索引index处的节点有左孩子,证明此时index节点不是叶子节点
- while (leftChild(index) < size) {
- //maxIndex记录的是index节点左右孩子中最大值的索引
- int maxIndex = leftChild(index);
- //右孩子的索引小于size意味着index节点含有右孩子
- if (rightChild(index) < size && nodeArray[rightChild(index)] > nodeArray[maxIndex]) {
- maxIndex = rightChild(index);
- }
- //如果index节点值比左右孩子值都大,则终止循环
- if (nodeArray[index] >= nodeArray[maxIndex]) {
- break;
- }
- //否则进行交换,将index指向其交换的左孩子或右孩子,继续向下循环,直到叶子节点
- swap(index, maxIndex);
- index = maxIndex;
- }
- }
-
- private void add(int value) {
- nodeArray[size++] = value;
- //构建大顶堆
- siftUp(size - 1);
- }
-
- private void extractMax() {
- /*
- 将堆顶元素和最后一个元素进行交换
- 此时并没有删除元素,而只是将size-1,剩下的元素重新构建成大顶堆
- */
- swap(0, --size);
- //重新构建大顶堆
- siftDown(0);
- }
-
- public int[] heapSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- nodeArray = new int[array.length];
- for (int value : array) {
- add(value);
- }
- for (int ignored : array) {
- extractMax();
- }
- return nodeArray;
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public int[] mergeSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- return mergeSort(array, 0, array.length - 1);
- }
-
- private int[] mergeSort(int[] array, int left, int right) {
- if (left < right) {
- //这里没有选择“(left + right) / 2”的方式,是为了防止数据溢出
- int mid = left + ((right - left) >>> 1);
- // 拆分子数组
- mergeSort(array, left, mid);
- mergeSort(array, mid + 1, right);
- // 对子数组进行合并
- merge(array, left, mid, right);
- }
- return array;
- }
-
- private void merge(int[] array, int left, int mid, int right) {
- int[] temp = new int[right - left + 1];
- // p1和p2为需要对比的两个数组的指针,k为存放temp数组的指针
- int p1 = left, p2 = mid + 1, k = 0;
- while (p1 <= mid && p2 <= right) {
- if (array[p1] <= array[p2]) {
- temp[k++] = array[p1++];
- } else {
- temp[k++] = array[p2++];
- }
- }
- // 把剩余的数组直接放到temp数组中
- while (p1 <= mid) {
- temp[k++] = array[p1++];
- }
- while (p2 <= right) {
- temp[k++] = array[p2++];
- }
- // 复制回原数组
- for (int i = 0; i < temp.length; i++) {
- array[i + left] = temp[i];
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- private static final int THRESHOLD = 47;
-
- public int[] quickSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- return quickSort(array, 0, array.length - 1);
- }
-
- private int[] quickSort(int[] array, int start, int end) {
- // 如果当前需要排序的数据量小于等于THRESHOLD则走插入排序的逻辑,否则继续走快速排序
- if (end - start <= THRESHOLD - 1) {
- return insertSort(array);
- }
-
- // left和right指针分别指向array的第一个和最后一个元素
- int left = start, right = end;
-
- /*
- 取最左边、最右边和最中间的三个元素的中间值作为基准数据,以此来尽量避免每次都取第一个值作为基准数据、
- 时间复杂度可能退化为O(n^2)的情况出现
- */
- int middleOf3Indexs = middleOf3Indexs(array, start, end);
- if (middleOf3Indexs != start) {
- swap(array, middleOf3Indexs, start);
- }
-
- // temp存放的是array中需要比较的基准数据
- int temp = array[start];
-
- while (left < right) {
- // 首先从right指针开始比较,如果right指针位置处数据大于temp,则将right指针左移
- while (left < right && array[right] >= temp) {
- right--;
- }
- // 如果找到一个right指针位置处数据小于temp,则将right指针处数据赋给left指针处
- if (left < right) {
- array[left++] = array[right];
- }
- // 然后从left指针开始比较,如果left指针位置处数据小于temp,则将left指针右移
- while (left < right && array[left] <= temp) {
- left++;
- }
- // 如果找到一个left指针位置处数据大于temp,则将left指针处数据赋给right指针处
- if (left < right) {
- array[right--] = array[left];
- }
- }
- // 当left和right指针相等时,此时循环跳出,将之前存放的基准数据赋给当前两个指针共同指向的数据处
- array[left] = temp;
- // 一次替换后,递归交换基准数据左边的数据
- if (start < left - 1) {
- array = quickSort(array, start, left - 1);
- }
- // 之后递归交换基准数据右边的数据
- if (right + 1 < end) {
- array = quickSort(array, right + 1, end);
- }
- return array;
- }
-
- private int middleOf3Indexs(int[] array, int start, int end) {
- int mid = start + ((end - start) >>> 1);
- if (array[start] < array[mid]) {
- if (array[mid] < array[end]) {
- return mid;
- } else {
- return array[start] < array[end] ? end : start;
- }
- } else {
- if (array[mid] > array[end]) {
- return mid;
- } else {
- return array[start] < array[end] ? start : end;
- }
- }
- }
-
- private void swap(int[] array, int i, int j) {
- array[i] = array[i] ^ array[j];
- array[j] = array[i] ^ array[j];
- array[i] = array[i] ^ array[j];
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public int[] countingSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- //记录待排序数组中的最大值
- int max = array[0];
- //记录待排序数组中的最小值
- int min = array[0];
- for (int i : array) {
- if (i > max) {
- max = i;
- }
- if (i < min) {
- min = i;
- }
- }
- int[] temp = new int[max - min + 1];
- //记录每个数出现的次数
- for (int i : array) {
- temp[i - min]++;
- }
- int index = 0;
- for (int i = 0; i < temp.length; i++) {
- //当输出一个数之后,当前位置的计数就减一,直到减到0为止
- while (temp[i]-- > 0) {
- array[index++] = i + min;
- }
- }
- return array;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public int[] stableCountingSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- //记录待排序数组中的最大值
- int max = array[0];
- //记录待排序数组中的最小值
- int min = array[0];
- for (int i : array) {
- if (i > max) {
- max = i;
- }
- if (i < min) {
- min = i;
- }
- }
- int[] temp = new int[max - min + 1];
- //记录每个数出现的次数
- for (int i : array) {
- temp[i - min]++;
- }
- //将temp数组进行转换,记录每个数在最后排好序的数组中应该要存放的位置+1(如果有重复的就记录最后一个)
- for (int j = 1; j < temp.length; j++) {
- temp[j] += temp[j - 1];
- }
- int[] sortedArray = new int[array.length];
- //这里必须是从后往前遍历,以此来保证稳定性
- for (int i = array.length - 1; i >= 0; i--) {
- sortedArray[temp[array[i] - min] - 1] = array[i];
- temp[array[i] - min]--;
- }
- return sortedArray;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public int[] bucketSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- //记录待排序数组中的最大值
- int max = array[0];
- //记录待排序数组中的最小值
- int min = array[0];
- for (int i : array) {
- if (i > max) {
- max = i;
- }
- if (i < min) {
- min = i;
- }
- }
- //计算桶的数量(可以自定义实现)
- int bucketNumber = (max - min) / array.length + 1;
- List<Integer>[] buckets = new ArrayList[bucketNumber];
- //计算每个桶存数的范围(可以自定义实现或者不用实现)
- int bucketRange = (max - min + 1) / bucketNumber;
-
- for (int value : array) {
- //计算应该放到哪个桶中(可以自定义实现)
- int bucketIndex = (value - min) / (bucketRange + 1);
- //延迟初始化
- if (buckets[bucketIndex] == null) {
- buckets[bucketIndex] = new ArrayList<>();
- }
- //放入指定的桶
- buckets[bucketIndex].add(value);
- }
- int index = 0;
- for (List<Integer> bucket : buckets) {
- //对每个桶进行内部排序,我这里使用的是快速排序,也可以使用别的排序算法,当然也可以继续递归去做桶排序
- quickSort(bucket);
- if (bucket == null) {
- continue;
- }
- //将不为null的桶中的数据按顺序写回到array数组中
- for (Integer integer : bucket) {
- array[index++] = integer;
- }
- }
- return array;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public int[] radixSort(int[] array) {
- if (array == null || array.length < 2) {
- return array;
- }
-
- //记录待排序数组中的最大值
- int max = array[0];
- for (int i : array) {
- if (i > max) {
- max = i;
- }
- }
- //获取最大值的位数
- int maxDigits = 0;
- while (max != 0) {
- max /= 10;
- maxDigits++;
- }
- //用来计数排序的临时数组
- int[] temp = new int[10];
- //用来存放每轮排序后的结果
- int[] sortedArray = new int[array.length];
- for (int d = 1; d <= maxDigits; d++) {
- //每次循环开始前都要清空temp数组中的值
- replaceArray(temp, null);
- //记录每个数出现的次数
- for (int a : array) {
- temp[getNumberFromDigit(a, d)]++;
- }
- //将temp数组进行转换,记录每个数在最后排好序的数组中应该要存放的位置+1(如果有重复的就记录最后一个)
- for (int j = 1; j < temp.length; j++) {
- temp[j] += temp[j - 1];
- }
- //这里必须是从后往前遍历,以此来保证稳定性
- for (int i = array.length - 1; i >= 0; i--) {
- int index = getNumberFromDigit(array[i], d);
- sortedArray[temp[index] - 1] = array[i];
- temp[index]--;
- }
- //一轮计数排序过后,将这次排好序的结果赋值给原数组
- replaceArray(array, sortedArray);
- }
- return array;
- }
-
- private final static int[] sizeTable = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
-
- /**
- * 获取指定位数上的数字是多少
- */
- private int getNumberFromDigit(int number, int digit) {
- if (digit < 0) {
- return -1;
- }
- return (number / sizeTable[digit - 1]) % 10;
- }
-
- private void replaceArray(int[] originalArray, int[] replaceArray) {
- if (replaceArray == null) {
- for (int i = 0; i < originalArray.length; i++) {
- originalArray[i] = 0;
- }
- } else {
- for (int i = 0; i < originalArray.length; i++) {
- originalArray[i] = replaceArray[i];
- }
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- <table style="text-align: center;">
- <tr>
- <td rowspan="2">排序算法</td>
- <td colspan="3">时间复杂度</td>
- <td rowspan="2">空间复杂度</td>
- <td rowspan="2">稳定性</td>
- </tr>
- <tr>
- <td>平均情况</td>
- <td>最好情况</td>
- <td>最坏情况</td>
- </tr>
- <tr>
- <td>冒泡排序</td>
- <td>O(n<sup>2</sup>)</td>
- <td>O(n)</td>
- <td>O(n<sup>2</sup>)</td>
- <td>O(1)</td>
- <td>稳定</td>
- </tr>
- <tr>
- <td>选择排序</td>
- <td>O(n<sup>2</sup>)</td>
- <td>O(n<sup>2</sup>)</td>
- <td>O(n<sup>2</sup>)</td>
- <td>O(1)</td>
- <td>不稳定</td>
- </tr>
- <tr>
- <td>插入排序</td>
- <td>O(n<sup>2</sup>)</td>
- <td>O(n)</td>
- <td>O(n<sup>2</sup>)</td>
- <td>O(1)</td>
- <td>稳定</td>
- </tr>
- <tr>
- <td>希尔排序</td>
- <td colspan="3">取决于增量的选择</td>
- <td>O(1)</td>
- <td>不稳定</td>
- </tr>
- <tr>
- <td>堆排序</td>
- <td>O(nlog<sub>2</sub>n)</td>
- <td>O(nlog<sub>2</sub>n)</td>
- <td>O(nlog<sub>2</sub>n)</td>
- <td>O(1)</td>
- <td>不稳定</td>
- </tr>
- <tr>
- <td>归并排序</td>
- <td>O(nlog<sub>2</sub>n)</td>
- <td>O(nlog<sub>2</sub>n)</td>
- <td>O(nlog<sub>2</sub>n)</td>
- <td>O(n)</td>
- <td>稳定</td>
- </tr>
- <tr>
- <td>快速排序</td>
- <td>O(nlog<sub>2</sub>n)</td>
- <td>O(nlog<sub>2</sub>n)</td>
- <td>O(n<sup>2</sup>)</td>
- <td>O(nlog<sub>2</sub>n)</td>
- <td>不稳定</td>
- </tr>
- <tr>
- <td>计数排序</td>
- <td>O(n+k)</td>
- <td>O(n+k)</td>
- <td>O(n+k)</td>
- <td>O(k)</td>
- <td>稳定</td>
- </tr>
- <tr>
- <td>桶排序</td>
- <td colspan="3">取决于桶散列的结果和内部排序算法的时间复杂度</td>
- <td>O(n+l)</td>
- <td>稳定</td>
- </tr>
- <tr>
- <td>基数排序</td>
- <td>O(d*(n+r))</td>
- <td>O(d*(n+r))</td>
- <td>O(d*(n+r))</td>
- <td>O(n+r)</td>
- <td>稳定</td>
- </tr>
- </table>
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- class Solution {
- public ListNode getKthFromEnd(ListNode head, int k) {
- if(head==null||k<=0)
- {
- return null;
- }
- //定义两个指针节点
- ListNode pre=head;
- ListNode last=head;
- //先将一个节点往后移动k-1个距离
- while(pre!=null && k>0){
- pre=pre.next;
- k--;
- }
- //一起移动,第一个节点移动到末尾,第二个结点移动到倒数第k个节点
- while(pre!=null)
- {
- pre=pre.next;
- last=last.next;
- }
- return last;
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- boolean hasCycle(ListNode head){
- ListNode fast, slow;
- fast = slow = head;
- while(fast != null && fast.next != null){
- fast = fast.next.next;
- slow = slow.next;
- if(slow == fast){
- return true;
- }
- }
- return false;
- }
- class Solution {
- public int[] twoSum(int[] nums, int target) {
- int i=0, j=nums.length-1;
- while(i<j){
- int s=nums[i]+nums[j];
- if(s<target) i++;
- else if(s>target) j--;
- else return new int[] {nums[i], nums[j]};
- }
- return new int[0];
- }
- }
- class Solution {
- public int[] exchange(int[] nums) {
- int left=0,right=nums.length-1;
- int tmp;
- while(left<right){
- if(nums[left]%2==1) left++;
- else if(nums[right]%2==0) right--;
- else{
- tmp=nums[left];
- nums[left]=nums[right];
- nums[right]=tmp;
- left++;
- right--;
- }
- }
- return nums;
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- import java.util.Scanner;
-
- public class Queue {
- public static void main(String[] args){
- ArrayQueue arrayQueue=new ArrayQueue(5);//4.方便测试所以没有定义太大
-
- char key=' ';//5.键盘交互,接收用户输入
- Scanner scanner=new Scanner(System.in);
-
- boolean loop=true;
- while(loop){
- System.out.println("s(show):显示队列");
- System.out.println("e(exit):退出程序");
- System.out.println("a(add):向队列添加元素");
- System.out.println("g(get):向队列取出元素");
- System.out.println("h(head):查看队列的头数据");
-
- key=scanner.next().charAt(0);
- if (key<97) key+=32; //实现大小写都可判断
-
- switch (key){
- case 's' :
- arrayQueue.showQueue();
- break;
-
- case 'a':
- System.out.println("请输入一个数字");
- arrayQueue.addQueue(scanner.nextInt());
- break;
-
- case 'g' :
- try {
- System.out.println("您取到的数据为:"+ arrayQueue.getQueue());
-
- } catch (Exception e){
- System.out.println(e.getMessage());
- }break;
-
-
- case 'h' :
- try {
- System.out.println("当前的头数据为:"+ arrayQueue.headQueue());
-
- } catch (Exception e){
- System.out.println(e.getMessage());
- }break;
-
- case 'e' :
- scanner.close();//关闭输入
- loop=false;
- break;
- }
- }
- System.out.println("**********程序已退出*********");
- }
- }
-
- class ArrayQueue{//1.创建一个实现队列的类
-
- private int MaxSize; //队列的最大存储容量
- private int [] array; //要存储队列的数组
-
- private int front; //取出时移动的指针,指向队列前的一个位置;
- private int rear; //存储时移动的指针,指向队列当前存储到的位置(最后一个数据);
-
- //创建队列
- public ArrayQueue(int arrMaxSize){//2.设置构造器
- MaxSize=arrMaxSize;
- rear=-1;front=-1;
- array=new int[MaxSize];
- }
-
- //判断队列是否空
- public boolean isEmpty(){//3.一些必要的方法
- return rear==front;
- }
-
- //判断队列是否满
- public boolean isFull(){
- return rear==MaxSize-1;
- }
-
- //添加数据
- public void addQueue(int q){
- if(isFull()) System.out.println("队列已满,不可添加数据!");
- else {
- array[++rear]=q;//java可以这么写
- System.out.println("添加数据成功");
- }
- }
-
- //取出数据
- public int getQueue(){
- if (!isEmpty()){
- return array[++front];
- }
- throw new RuntimeException("队列为空");//没有合适的返回值,用异常
-
- }
-
- //显示当前队列所有数据
- public void showQueue(){
- if (isEmpty()) {
- System.out.println("队列为空,无可打印数据");
- return;
- }
- for (int i=0;i<array.length;i++){
- System.out.printf("%d ",array[i]);
- }
- System.out.println();
- }
-
- //返回当前队列的头数据
- public int headQueue(){
- if (isEmpty()) throw new NumberFormatException("队列为空,无头数据");
- return array[front+1];
-
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。