JAVA - A Perpetually-Sorted Array

来源:百度知道 编辑:UC知道 时间:2024/06/17 16:37:17
Many applications require a list of values to remain in sorted order, even if new values are added to the list (or old values are removed). It can be very expensive (in terms of CPU time) to continually re-sort the array every time a new value is added. A better approach is to insert new values in their proper place as they are added to the list, shifting elements down as necessary.

Complete the SortedIntegerArray class (provided in the SortedIntegerArray.txt file). This class contains two instance variables: an int array (do NOT use an ArrayList!), and an integer that tracks how many values are currently stored in the array (a number between 0 and the length of the array).

Fill in the bodies of the following methods for your new data type:

1.SortedIntegerArray(): This constructor takes a single int argument. The constructor should set the size instance variable to 0 (the array is empty) and creates a new integer array large enough to hold the specif

//插入排序...-_-!~

import java.util.*;

public class SortedIntegerArray {

private final static int DEFOURT_LENGTH = 100;
private int[] values;
private int size;
private int arrLength = 0;

public SortedIntegerArray(int startingSize) {
size = 0;
values = new int[startingSize];
arrLength = startingSize;
}

public SortedIntegerArray() {
size = 0;
values = new int[SortedIntegerArray.DEFOURT_LENGTH];
arrLength = SortedIntegerArray.DEFOURT_LENGTH;
}

public int size() {
return size;
}

public int get(int position) {
if (position >= size()) {
System.out.println("get position " + position + " failed!");
return -1;
} else {
return values[position];
}

}

public void print() {
for (int i = 0; i < size(); i++) {
System.out.print(va