协助使用快速排序算法,在一个数组中处理字母和数字字符值[关闭]。

问题描述 投票:1回答:1

我正在写一个程序,接受一个输入。这个输入被放置在不同的数组中。每个数组都是'char'数据类型。我需要将每个数组的值从最大到最小组织起来。每个数组代表扑克牌中的一种花色:红桃,黑桃等。需要组织的值就是这些牌的值。顺序层次结构如下。A到K到Q到J到T(代表'10'),然后是9到8到7到6到5到4到3到2。 我的问题是实现快速排序算法,使其既能处理字母又能处理数字。下面是我的方法。

public static void quickSort (int a[], int start, int end)
{
if (start < end)
{ 
  int split = partition (a, start, end);

   // show split
  System.out.println ("split " + split);
  System.out.println ("");

   // sort the left sublist
  quickSort (a, start, split);

   // now sort the right sublist
  quickSort (a, split + 1, end);
  }
}

public static int partition (int a[], int start, int end)
{ 
int bottom = start - 1;
int top = end + 1;

 // pick a value pivot.Arrange the list according to: <= or >= to pivot

int pivot = a [start];

System.out.println ("pivot is " + pivot);

 // walk bottom and top towards each other, using them to swap array
 // elements as we go, and stopping when bottom and top pass each other

while (bottom < top)
{
   // walk until you find an element that is not in its current sublist

  do
  {
    bottom++;
  }
  while (a [bottom] < pivot);

  do
  {
    top--;
  }
  while (a [top] > pivot);

   // swap a[bottom] and a[top], thus putting the values in the
   // correct sublist

  int temp = a [bottom];
  a [bottom] = a [top];
  a [top] = temp;
}

 // undo the last swap that took place after the bottom and top
 // indices passed each other

int temp = a [bottom];
a [bottom] = a [top];
a [top] = temp;

 // finally, return split index
return top;

}
}

输入 4C3C6CTSTHAD2S8DACQHKS2D4H 预期输出:黑桃K 10 2红心Q 10 4方块A 8 2梅花A 6 4 3

我得到的输出是失序的。我为每个花色调用了一次方法。

java arrays sorting char quicksort
1个回答
1
投票

我按照以下步骤将每一种花色的牌按相反的顺序进行排序。

Step1.读取输入的字符串,并按2个字符的长度进行分割。 读取输入字串,并按2的长度分割,因为输入字串中的每张牌都代表2个字符。例如,输入的字符串'6CTS'表示牌是梅花6和黑桃10。

Step2.将输入的牌从字符串表示法修改为字符串表示法。 将输入的牌从字符串表示法修改为数字表示法。我们想使用你实现的quicksort函数。你的quicksort需要输入数组为整数类型,所以我将输入的字符串修改为这种格式。例如,TS会变成黑桃10。JH会变成心型的11,以此类推。

Step3.用你的quicksort方法对输入的字符串进行排序,比如TS会变成黑桃10,JH会变成红桃11,等等。 用你的quicksort方法对每个花色进行迭代排序.

上述方法的实现在下面的片段中。

import com.google.common.primitives.Ints;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {

    public static void quickSort(int a[], int start, int end) {
        if (start < end) {
            int split = partition(a, start, end);

            // show split
//            System.out.println("split " + split);

            // sort the left sublist
            quickSort(a, start, split);

            // now sort the right sublist
            quickSort(a, split + 1, end);
        }
    }

    public static int partition(int a[], int start, int end) {
        int bottom = start - 1;
        int top = end + 1;

        // pick a value pivot.Arrange the list according to: <= or >= to pivot

        int pivot = a[start];

//        System.out.println("pivot is " + pivot);

        // walk bottom and top towards each other, using them to swap array
        // elements as we go, and stopping when bottom and top pass each other

        while (bottom < top) {
            // walk until you find an element that is not in its current sublist

            do {
                bottom++;
            }
            while (a[bottom] < pivot);

            do {
                top--;
            }
            while (a[top] > pivot);

            // swap a[bottom] and a[top], thus putting the values in the
            // correct sublist

            int temp = a[bottom];
            a[bottom] = a[top];
            a[top] = temp;
        }

        // undo the last swap that took place after the bottom and top
        // indices passed each other

        int temp = a[bottom];
        a[bottom] = a[top];
        a[top] = temp;

        // finally, return split index
        return top;

    }

    public static void main(String[] args) {
        Map<String, Integer> cardValueMap = new HashMap<>();
        // append the value as per the priority of the card
        cardValueMap.put("T", 10);
        cardValueMap.put("J", 11);
        cardValueMap.put("Q", 12);
        cardValueMap.put("K", 13);
        cardValueMap.put("A", 14);
        String inputString = "4C3C6CTSTHAD2S8DACQHKS2D4H";
        readInput(inputString, cardValueMap);
    }

    static void readInput(String inputString, Map<String, Integer> cardValueMap) {
        String[] cardInput = splitToNChar(inputString, 2); // each input is of size 2 as per the problem
        Map<String, List<Integer>> allCardMap = new HashMap<>();
        for (String eachCard : cardInput) {
            String[] tempCardToProcess = splitToNChar(eachCard, 1);
            List<Integer> existingList = allCardMap.get(tempCardToProcess[1]);
            if (existingList == null) {
                existingList = new ArrayList<>();
            }

            existingList.add(getNumericValueOfCard(tempCardToProcess[0], cardValueMap));
            allCardMap.put(tempCardToProcess[1], existingList);
        }

        System.out.println("allCardMap before sorting is = " + allCardMap);

        for (Map.Entry<String, List<Integer>> entry : allCardMap.entrySet()) {
            String suitType = entry.getKey();
            List<Integer> presentCardList = entry.getValue();
            List<Integer> sortedPresentCardList = getSortedUsingQuickSort(presentCardList);
            Collections.reverse(sortedPresentCardList); // needed in reverse order
            allCardMap.put(suitType, sortedPresentCardList);
        }
        System.out.println("allCardMap after sorting is = " + allCardMap);
        // Do the post processing of the output as per your requirement.
        // For example if you want to see D as diamond, S as spade. Print accordingly.
    }

    /**
     * Split text into n number of characters.
     *
     * @param text the text to be split.
     * @param size the split size.
     * @return an array of the split text.
     */
    private static String[] splitToNChar(String text, int size) {
        List<String> parts = new ArrayList<>();

        int length = text.length();
        for (int i = 0; i < length; i += size) {
            parts.add(text.substring(i, Math.min(length, i + size)));
        }
        return parts.toArray(new String[0]);
    }

    static Integer getNumericValueOfCard(String cardString, Map<String, Integer> cardValueMap) {
        boolean isNumeric = cardString.chars().allMatch(Character::isDigit);
        Integer valueToInsert;
        if (!isNumeric) {
            valueToInsert = cardValueMap.get(cardString);
        } else {
            valueToInsert = Integer.valueOf(cardString);
        }
        return valueToInsert;
    }

    static List<Integer> getSortedUsingQuickSort(List<Integer> cardList) {
        int[] suitArray = Ints.toArray(cardList);
        quickSort(suitArray, 0, suitArray.length - 1);
        return Arrays.stream(suitArray)        // IntStream
                .boxed()        // Stream<Integer>
                .collect(Collectors.toList());
    }

}

如果你在理解上面的代码时感到有任何困难,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.