[Data structure and algorithm] Vue3 realizes selection sorting animation effect and principle dismantling

Series Article Directory

Remove duplicates in an ordered array
JavaScript implements selection sort



1. The principle of selection sort

Selection Sort is a simple sorting algorithm whose basic idea is to select the smallest (or largest) element from the data to be sorted, and then put it at the end (or beginning) of the sorted sequence. The time complexity of this algorithm is O(n^2), where n is the number of data to be sorted, so it is less efficient on large-scale data, but it is still an effective sorting method for small-scale data or partially ordered data method.

1.1, the basic steps of selection sort

1. Find the smallest element in the unsorted part.
2. Swap the smallest element with the first element of the unsorted part and include it in the sorted part.
3. Repeat steps 1 and 2 in the remaining unsorted parts until all elements are included in the sorted part.

1.2. Dismantling ideas

For example, the existing array arr = [ 6, 25, 15, 7 , 19 , 12 , 26 , 17 , 5 , 13 ], then the selection sort means

The first sorting is to start from the first position, traverse all the array data, find the smallest data, which is 5, and then exchange the position of 5 with the first element of the array, which is the position of arr[0];

5 25 15 7 19 12 26 17 6 13

In the second sorting, repeat the operation of the first round, find the minimum value 6, exchange to the position of arr[1], and get the following results:

5 6 15 7 19 12 26 17 25 13

...
After repeating (array arr length - 1) times, the entire array has become ordered

5 6 7 12 13 15 17 19 25 26

2. Animation demonstration principle

Please add a picture description

3. Code implementation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Select sort</title>

    <script>

        function selectionSort(arr) {
    
    
            let n = arr.length;

            for (let i = 0; i < n; i++) {
    
    
                let minIndex = i;
                for (let j = i + 1; j < n; j++) {
    
    
                    if (arr[j] < arr[minIndex]) {
    
    
                        minIndex = j;
                    }
                }

               	// 交换位置
                let temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
            }

            return arr;
        }

        // 示例
        let unsortedArray = [6, 25, 15, 7, 19, 12, 26, 17, 5, 13];
        document.write( "原始数组:", unsortedArray )
        document.write( "<br>" )

        let sortedArray = selectionSort(unsortedArray);
        document.write( "排序后的数组:", sortedArray )

    </script>


</head>
<body>

</body>
</html>

result:

Original array: 6,25,15,7,19,12,26,17,5,13
Sorted array: 5,6,7,12,13,15,17,19,25,26

4. Optimized selection sort

1. The number of traversals in the outer layer can be reduced once, and the last two pieces of data have been sorted after comparing and exchanging positions; 2.
When the first number in the inner layer is the minimum value, there is no need to generate a temporary variable, and there is no need to exchange with itself Location

		function selectionSort(arr) {
    
    
            let n = arr.length;

            for (let i = 0; i < n - 1; i++) {
    
    
                let minIndex = i;
                for (let j = i + 1; j < n; j++) {
    
    
                    if (arr[j] < arr[minIndex]) {
    
    
                        minIndex = j;
                    }
                }

                if (minIndex !== i) {
    
    
                    // 交换位置
                    let temp = arr[i];
                    arr[i] = arr[minIndex];
                    arr[minIndex] = temp;
                }
            }

            return arr;
        }

5. Use Vue3 to realize the animation effect of selection sorting (the animation effect diagram of the second part)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue3实现选择排序动画效果演示</title>
    <!-- Import element-plus style -->
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
    <!-- Import Vue 3 -->
    <script src="//unpkg.com/vue@3"></script>
    <!-- Import axios -->
    <script src="//unpkg.com/axios/dist/axios.min.js"></script>
    <!-- Import element-plus -->
    <script src="//unpkg.com/element-plus"></script>

</head>
<body>

    <div id="app">
        <div id="sort">
            <table cellspacing="0">
                <tr>
                    <template v-for="(data,index) in sortedData" :key="index">
                        <td>
                            <input type="button" :value="data" class="sortedData" :style="'height:'+ data * 10 + 'px' ">
                        </td>
                    </template>
                    <template v-for="(data,index) in data" :key="index">
                        <td>
                            <input v-if="sortingPoint==index" type="button" :value="data" :style="'height:'+ data * 10 + 'px;'" class="sortingBtn"  >
                            <input v-else-if="sortingMinPoint==index" type="button" :value="data" :style="'height:'+ data * 10 + 'px;'" class="sortingMinBtn"  >
                            <input v-else="sortingPoint!=index" type="button" :value="data" :style="'height:'+ data * 10 + 'px;'" >
                        </td>
                    </template>
                </tr>

            </table>

        </div>


    </div>

    <script>
        const App = {
     
     
            data(){
     
     
                return {
     
     
                    data: [ 6, 25, 15, 7 , 19 , 12 , 26 , 17 , 5 , 13 ] ,
                    loading: false,
                    timer:null, //定时器名称
                    sortedData:[] , //已排序字段
                    sortTimer:null, // 内排序延时器
                    sortingPoint:1, //正在排序的位置
                    sortingMinPoint:0 //正在排序时最小的位置
                }
            },
            mounted() {
     
     
                this.sortData();
                this.setTime();
            },
            methods:{
     
     
                setTime() {
     
     
                    //每隔一分钟运行一次保存方法
                    this.timer = setInterval(()=>{
     
     
                        // console.log("停顿6秒")
                        this.sortData();
                    }, 5000 )
                },
                setSortTime() {
     
     
                    //每隔一分钟运行一次保存方法
                    this.sortTimer = setInterval(()=>{
     
     
                        // console.log("停顿1秒")
                        this.sortMinData();
                    },1000)
                },
                sortData() {
     
     
                    let that = this;
                    this.setSortTime() ;
                },
                sortMinData() {
     
     

                    // 如果只剩一位数,不需要排序
                    if( this.data.length == 1 ) {
     
     
                        this.sortedData.push(this.data[this.sortingMinPoint]);
                        this.data = [];

                        clearInterval(this.sortTimer);  // 清除定时器
                        this.sortTimer = null;

                        clearInterval(this.timer);  // 清除定时器
                        this.timer = null;

                        console.log("排序完成")
                    } else {
     
     
                        //找到最小值的位置
                        if( this.data[this.sortingMinPoint] > this.data[this.sortingPoint] ) {
     
     
                            this.sortingMinPoint = this.sortingPoint;
                        }


                        if( this.sortingPoint == this.data.length -1 ) {
     
     
                            this.sortedData.push(this.data[this.sortingMinPoint]);
                            this.data.splice(this.sortingMinPoint, 1);

                            // 结束时重置为0
                            this.sortingPoint = 1;
                            this.sortingMinPoint = 0;

                            clearInterval(this.sortTimer);  // 清除定时器
                            this.sortTimer = null;

                        } else {
     
     
                            this.sortingPoint ++;
                        }
                    }
                }
            },
            beforeDestroy(){
     
     
                clearInterval(this.timer);  // 清除定时器
                this.timer = null;

                clearInterval(this.sortTimer);  // 清除定时器
                this.sortTimer = null;
            },

        }

        const App2 = Vue.createApp(App)
        App2.use(ElementPlus)
        App2.mount(app)
    </script>
</body>
<style >

    #sort {
     
     
        background-color: azure;
        height: 300px;
        width: 600px;
    }

    .sortingBtn {
     
     
        background-color: red;
    }
    .sortingMinBtn {
     
     
        background-color: aquamarine;
    }

    .sortedData {
     
     
        background-color: burlywood;
    }

    td{
     
     
        vertical-align: bottom;
    }

</style>

</html>

Guess you like

Origin blog.csdn.net/s445320/article/details/132183965
Recommended