我正在尝试在React JS中为项目创建排序可视化程序。
就目前而言,我仅实现了冒泡排序,但我计划还实现快速排序,合并排序等等
我如何添加一个很好的动画来逐步显示排序算法的基本工作原理?
每次更改时是否需要更新阵列,还是有其他方法可以做到?
SortingVisualizer.tsx
<?php
$str = '<ul><li><a href="https://www.example.com/profile/shrey">Shrey Chathly</a><p> shrey@yahoo.com</p><p> 9910212121</p></li><li><a href="https://www.example.com/profile/neminath">Neminath</a><p> 9818505051</p></li><li><a href="https://www.example.com/profile/mohan">Mohan</a><p> Mohan@yahoo.co.in</p><p> 9111502287</p></li><li><a href="https://www.example.com/profile/naina">Naina</a><p> naina@gmail.com</p><p> 9818505001</p></li><li><a href="https://www.example.com/profile/mohan">Rakesh</a><p> 9111502222</p></li></ul>';
$data = null;
$dom = new DOMDocument();
$dom->loadHTML($str);
$elements = $dom->getElementsByTagName('li');
foreach($elements as $key => $element) {
foreach($element->getElementsByTagName('a') as $valueA) {
$data[$key][] = trim($valueA->textContent);
}
$pValues = $element->getElementsByTagName('p');
if(count($pValues) >= 2) {
$data[$key][] = trim($pValues[0]->textContent);
$data[$key][] = trim($pValues[1]->textContent);
} elseif (count($pValues) == 1) {
$data[$key][] = null;
$data[$key][] = trim($pValues[0]->textContent);
}
}
echo '<pre>';
print_r($data);
SortingVisualizer.css
import "./SortingVisualizer.css";
import React, { useEffect, useState } from "react";
import * as sortings from "../sortingAlgorithms";
// Change this value for the number of bars (value) in the array.
const NUMBER_OF_ARRAY_BARS = 50;
// This is the main color of the array bars.
const PRIMARY_COLOR = "turquoise";
function SortingVisualizer() {
const [array, setArray] = useState<number[]>([]);
const resetArray = () => {
const randomNumbers = [];
for (let i = 0; i < NUMBER_OF_ARRAY_BARS; i++) {
randomNumbers.push(randomIntFromInterval(5, 730));
}
setArray(randomNumbers);
};
const bubbleSort = () => {
setArray(sortings.bubbleSort(array.slice()));
};
useEffect(() => {
resetArray();
}, []);
return (
<div className="array-container">
{array.map((value, idx) => (
<div
className="array-bar"
key={idx}
style={{
backgroundColor: PRIMARY_COLOR,
height: `${value}px`,
}}
></div>
))}
<button onClick={bubbleSort}>Bubble Sort</button>
</div>
);
}
export default SortingVisualizer;
function randomIntFromInterval(min: number, max: number) {
// min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
sortingAlgorithms.ts
.array-container {
position: absolute;
left: 100px;
/* top: 100px; */
}
.array-bar {
width: 5px;
display: inline-block;
margin: 0 1px;
}