Automatic test of sorting method (only one line of code)

Last project address

https://gitee.com/yan-jiadou/study/tree/master/Java%E5%8A%A8%E6%89%8B%E5%81%9A%E4%B8%80%E5%81%9A/src/main/java/SortStudy

The test method has been written. The automatic test is adopted. You only need to call it. It is very simple. In this way, our energy can be focused on the algorithm implementation of SortCore. The automatic test here has its own data comparison function to test whether the implementation of your sorting method is correct. If there is a problem with the result, it will return false.

I objective

Some people say that I have learned the sorting method, but I just can't write it. Even if I write it, I find that it can't be used at all. Because the writing is too narrow, I can only sort numbers.
I am such a person. Recently, when reviewing the knowledge of algorithms, I was wondering if I could make a generic sorting collection tool from the sorting methods I learned, and combine various sorts to form such a tool and method:

/**
     * Sort method call
     * @param in
     * @param sortType maoPao--Bubble sort insert -- insert sort
     *                 shell--Hill sort quick
     *                 merge--Merge sort heap -- heap sort
     *                 counting--Count sort
     * @return Returns the sorted result
     */
    public static <T extends Comparable> Object[] Sort(T[] in,String sortType){
        if(sortType.equals("maoPao")){
            return SortCore.maoPaoSort(in);
        }
        if(sortType.equals("insert")){
            return SortCore.InsertionSort(in);
        }
        if(sortType.equals("shell")){
            return SortCore.ShellSort(in,in.length-1);
        }
        if(sortType.equals("quick")){
            return SortCore.quickSort(in,0,in.length-1);
        }
        if(sortType.equals("merge")){
            return SortCore.mergeSort(in,0,in.length-1);
        }
//        if(sortType.equals("heap")){
//            return new SortCore.Heap().Heapsort(null,in,in.length);
//        }

        return null;
    }

In this way, I can use that sort if I want to use that sort. It is also convenient to review the sort method and optimize learning, rather than scattered learning.

II realization

With this idea, I began to do it. I put the implementation of various sorting in one class for other classes to call, and then write a tool method to simplify our calling operation.
Well, now that the sorting is written, here is how to test. If you manually create an array for testing, it will be troublesome and time-consuming, so I wrote an automatic random array generator to help me create an array:

 /**
     * Random array generator, this method can generate arrays of ordinary number type, floating number type and string type
     * Recommended: Integer type Integer floating number type Double String type String
     * @param type Element type
     * @param count Array size
     * @param <T> generic types 
     * @return Returns the generated array
     */
    public static <T extends Comparable> Object[] makeRandomArray(T type,Integer count) throws Exception {
        Object[] result=new Object[count];
        Class cl=type.getClass();
        Constructor[] constructors=cl.getDeclaredConstructors();
        Constructor constructor=null;
        for(Constructor constructor1:constructors){
            Class[] types = constructor1.getParameterTypes();
            if(types.length==1&&types[0]==String.class){
                constructor=constructor1;
                break;
            }
        }
        if(constructor==null){
            throw new Exception("This type does not support generating random types");
        }
        for(int i=0;i<count;i++){
            String emuStr=null;
            double emu = 0;
            if(type.getClass()==String.class){
                int strLength=(int)(Math.random()*10);
                if(strLength<1){
                    strLength=1;
                }
                StringBuilder strBul=new StringBuilder();
                for(int j=0;j<strLength;j++){
                    int num=(int)(Math.random()*122);
                    while (num<97){
                        num=(int)(Math.random()*122);
                    }
                    char letter=(char) num;
                    strBul.append(letter);
                }
                emuStr=strBul.toString();
            }else{
                emu=(Math.random()*1000);
                emuStr= Double.toString(emu);
            }
            try{
                result[i]=constructor.newInstance(emuStr);
            }catch (Exception e){
                int emuInt=(int)emu;
                emuStr=Integer.toString(emuInt);
                result[i]=constructor.newInstance(emuStr);
            }
        }
        return  result;
    }

III test

Manual test comparison is very troublesome, so it's better to arrange it again with the sort provided by jdk, and then compare the results directly

 /**
     * Test method is used to test the sorting method
     * @param obj Type of test required
     * @return Return test results
     */
    public static <T extends Comparable> boolean sortTest(T obj,String type,int count){
        Object[] testResults = new Object[0];
        try{
            testResults=SortUtil.makeRandomArray(obj,count);
            Object[] arraySort=new Object[testResults.length];
            T[] result= (T[])Array.newInstance(obj.getClass(),testResults.length);
            int i=0;
            for(Object object:testResults){
                File file=new File("temp");
                if(file.exists()){
                    boolean flag=file.delete();
                }
                FileOutputStream fileOut = new FileOutputStream("temp");//Define the file byte output stream, and the source is temp
                ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);//Define object byte output stream
                objectOut.writeObject(object);//Writes object serialization information to the source
                objectOut.close();//Close object output stream
                FileInputStream fileIn = new FileInputStream("temp");//Define the file input stream. The source is temp
                ObjectInputStream objectIn = new ObjectInputStream(fileIn);//Define object byte input stream
                Object target = (T)objectIn.readObject();//Read out the object in the source to obtain the clone of the object
                objectIn.close();//Close object input stream
                arraySort[i]=target;
                result[i]=(T)object;
                i++;
            }
            testResults=SortUtil.Sort(result,type);
            Arrays.sort(arraySort);

            for(int n=0;n<testResults.length;n++){
                if(!testResults[n].equals(arraySort[n])){
                    return false;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

Here is the main method:

public static void main(String[] args) {
        System.out.println(sortTest(new Integer(10),"maoPao",10));
    }

Yes, it's very simple. It only takes one line of code to complete the automatic test!!!
result:

Keywords: Java Algorithm

Added by pulsedriver on Mon, 27 Dec 2021 13:28:58 +0200