2.线性表(一,线性表的顺序存储结构,穷举法(冒泡和选择排序))

线性表

顺序表
  1. 顺序表的特性
  • 顺序表的元素有前驱和后继
  • 顺序表有size
  1. 顺序表的增删改查
public class OrderList {

    public int[] arrs = new int[14];
    
    int size = arrs.length;

    public void add(int index ,int x){
        for (int i = index; i < arrs.length; i++) {
            arrs[i] = arrs[i+1];
        }
        arrs[index] = x;
        size++;
    }
    
    public void delete(int index){
        for (int i = index; i < arrs.length; i++) {
            arrs[i] = arrs[i-1];
        }
        arrs[arrs.length-1] = 0;
        size--;
    }
    
    public void change(int index,int x){
        arrs[index] = x;
    }

    public int search(int index){
        return arrs[index];
    }
    
}

  1. 顺序表的优缺点
    优点:尾插效率高,支持随机访问
    缺点:中间插入和删除效率低

蛮力法(枚举法,穷举法)

冒泡排序和选择排序
  1. 说明,适用于排序10个以内数据,比如QQ斗牛卡牌的排序
  2. 代码
import org.junit.Test;

public class SortTest {

    public void bubbleSort(Card[] cards){
        for (int j = cards.length-1; j > 0; j--) {
            boolean flag = true;
            for (int i = 0; i < j; i++) {
                if (cards[i].compareTo(cards[i+1])>0){
                    Card temp =  cards[i];
                    cards[i] = cards[i+1];
                    cards[i+1] = temp;
                    flag = false;
                }
            }
            if (flag){
                break;
            }
        }
    }

    public void selectSort(Card[] cards){
        for (int j = 0; j < cards.length-1; j++) {
            int index = j;
            for (int i = j+1; i < cards.length; i++) {
                if (cards[i].compareTo(cards[index])<0){
                    index = i;
                }
            }
            Card temp = cards[index];
            cards[index] = cards[j];
            cards[j] = temp;
        }
    }

    public Card[] cards = new Card[]{
      new Card(4,2),
            new Card(2,2),
            new Card(1,1),
            new Card(6,3),
            new Card(5,4),
            new Card(7,2),
            new Card(3,1),
    };

    public void printArray(Card[] cards){
        for (Card card : cards) {
            System.out.println(card.toString());
        }
    }

    @Test
    public void Test(){
        printArray(cards);

        System.out.println("-------");

        bubbleSort(cards);
        printArray(cards);

        System.out.println("-------");

        selectSort(cards);
        printArray(cards);
    }
}

public class Card implements Comparable{
    public int cardPoint;
    public int pokerColor;

    public Card(int cardPoint, int pokerColor) {
        this.cardPoint = cardPoint;
        this.pokerColor = pokerColor;
    }

    @Override
    public int compareTo(Object o) {
        Card c = (Card) o;
        if (c.cardPoint>this.cardPoint){
            return 1;
        }else if(c.cardPointthis.pokerColor){
            return 1;
        }else if (c.pokerColor

你可能感兴趣的:(2.线性表(一,线性表的顺序存储结构,穷举法(冒泡和选择排序)))