线性表操作可视化及排序运算时间检测代码C#
时间: 2023-08-06 12:10:04 浏览: 111
数据结构实验代码线性表的基本操作.rar
以下是一个简单的线性表操作可视化的示例代码:
```csharp
using System;
using System.Collections.Generic;
namespace LinearListVisualization
{
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
Console.WriteLine("Linear List Visualization");
Console.WriteLine("--------------------------");
while (true)
{
Console.WriteLine("1. Insert");
Console.WriteLine("2. Delete");
Console.WriteLine("3. Print");
Console.WriteLine("4. Exit");
Console.Write("Enter your choice: ");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
Console.Write("Enter the value to insert: ");
int value = int.Parse(Console.ReadLine());
list.Add(value);
Console.WriteLine("{0} inserted into the list.", value);
break;
case 2:
if (list.Count == 0)
{
Console.WriteLine("The list is empty.");
}
else
{
Console.Write("Enter the index to delete: ");
int index = int.Parse(Console.ReadLine());
if (index < 0 || index >= list.Count)
{
Console.WriteLine("Invalid index.");
}
else
{
int deletedValue = list[index];
list.RemoveAt(index);
Console.WriteLine("{0} deleted from the list.", deletedValue);
}
}
break;
case 3:
Console.WriteLine("The list contains:");
foreach (int item in list)
{
Console.Write("{0} ", item);
}
Console.WriteLine();
break;
case 4:
Console.WriteLine("Exiting...");
return;
default:
Console.WriteLine("Invalid choice.");
break;
}
}
}
}
}
```
此代码使用 `List<int>` 类型实现线性表,并提供了插入、删除、打印和退出操作。
以下是一个简单的排序运算时间检测代码,使用冒泡排序算法:
```csharp
using System;
namespace SortingTimeTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Sorting Time Test");
Console.WriteLine("------------------");
Console.Write("Enter the size of the array: ");
int size = int.Parse(Console.ReadLine());
int[] array = new int[size];
Random random = new Random();
for (int i = 0; i < size; i++)
{
array[i] = random.Next(100);
}
Console.WriteLine("Original array:");
PrintArray(array);
Console.WriteLine("Sorting...");
DateTime startTime = DateTime.Now;
BubbleSort(array);
DateTime endTime = DateTime.Now;
Console.WriteLine("Sorted array:");
PrintArray(array);
TimeSpan elapsedTime = endTime - startTime;
Console.WriteLine("Time elapsed: {0} milliseconds", elapsedTime.TotalMilliseconds);
}
static void BubbleSort(int[] array)
{
int n = array.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (array[j] > array[j + 1])
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
static void PrintArray(int[] array)
{
foreach (int item in array)
{
Console.Write("{0} ", item);
}
Console.WriteLine();
}
}
}
```
此代码使用 `int[]` 数组实现排序,使用冒泡排序算法进行排序,并输出排序后的数组和排序所花费的时间。
阅读全文