我有一个名为WordSort(worddata [],int )的函数,它提供了两个变量1- worddata是保存文件中给定单词的信息的数组。count只是一个计数器变量,用于查看我们正在查看的数组中的哪个单词。
在这个程序中读取的words.txt文件将是一串单词。
this is a list of words
there are letters and numbers
23 people recommend this program.以下是功能:
void WordSort (worddata W [], int count)
{
for (int i=1; i < count; i++)
{
for (int j=i; j > 0 && W[j-1].word > W[j].word; j--)
{
Swap(W[j], W[j-1]);
}
}
}交换函数应该与前面的元素交换,只要j>0,或者列表结束。我对如何完成交换函数感到困惑,下面是我得到的例子。
void Swap (worddata & a, worddata & b)
{
int += a;
a = b;
b =+;
}交换应该将每个元素与其前面的元素交换。
我认为WordSort函数工作得很好,唯一缺少的就是交换函数。有人能为我指出正确的方向或解释插入排序更好吗?
发布于 2013-09-10 00:53:53
交换应该是这样的--我不知道你的例子有多接近。
void Swap (worddata & a, worddata & b)
{
worddata temp = a;
a = b;
b = temp;
}发布于 2014-12-14 14:16:12
void insertion_sort()
{
/* Algorithm : Insertion Sort
* Coded by .
*/
int num;
/*
* Asking the User no of Integers he/she wants to enter
*/
cout << "Enter no of integers u want to enter: ";
cin >> num;
/* Creating an Array to store the integers*/
int s[num];
/*Taking Integers from the User */
for(int i = 0 ; i < num ; i++)
{
cout << "Integer " << i+1 << " is : ";
int x;
cin >> x;
s[i] = x;
}
/* The Magic of INSERTION SORT */
for(int j = 1 ; j <= (num-1) ; j++)
{
int key = s[j];
int k = j-1;
while(k >=0 && key <= s[k])
{
s[k+1] = s[k];
k = k - 1;
}
s[k+1]=key;
}
/*Printing Out the Sorted List */
cout << "The Sorted List is \n\n";
for(int i = 0 ; i < num ; i++)
{
cout << s[i] << " ";
}
}发布于 2013-09-10 01:07:16
使用标准库std:掉期代替。在你的循环中:
for (...)
{
std:swap(W[j], W[j-1]);
}交换要求worddata类具有一个副本构造函数和一个赋值操作符,这两个操作符是显式或隐式定义的。
https://stackoverflow.com/questions/18709163
复制相似问题